从继承的类访问父“this”变量

时间:2013-12-02 19:31:31

标签: javascript class inheritance

我知道这很简单,可能在某些地方,我不知道该找什么样的“类继承”?我正试图从货物中获取船舶的this功能。想法?

var Ship = function() {
    this.id = Math.floor(Math.random() * 1000000);
};

var Cargo = function(){
    this.id = Math.floor(Math.random() * 1000000);
}

Cargo.prototype.push = function(string){
    return string;
}

Ship.prototype.cargo = Cargo;

module.exports = Ship;

2 个答案:

答案 0 :(得分:1)

您可以使用下划线扩展对象或模仿其来源:

http://underscorejs.org/#extend

http://underscorejs.org/docs/underscore.html#section-78

编辑:我想你想要的是这个。

var Cargo, Ship, cargo;

Ship = (function() {
  function Ship() {}

  return Ship;

})();

Cargo = (function() {
  function Cargo(ship) {
    this.ship = ship;
  }

  return Cargo;

})();

cargo = new Cargo(new Ship());

alert(cargo.ship);

答案 1 :(得分:1)

原型的功能已经可以访问实例的this

var Ship=function () {
    this.id=Math.floor(Math.random()*1000000);
};

var Cargo=function () {
    this.id=Math.floor(Math.random()*1000000);
};

Cargo.prototype.push=function (string) {
    return string;
};

Ship.prototype.cargo=function () {
    var cargo=new Cargo();
    cargo.ship=this;
    return cargo;
};

var ship1=new Ship();
var cargo1=ship1.cargo();
var cargo2=ship1.cargo();
alert(cargo1.ship.id===cargo2.ship.id);

var ship2=new Ship();
var cargo3=ship2.cargo();
var cargo4=ship2.cargo();
alert(cargo3.ship.id===cargo4.ship.id);

alert(cargo1.ship.id===cargo3.ship.id);