访问父“;这个“;变量,来自继承类

Access parent "this" variables, from inherited class

本文关键字:继承 变量 这个 访问      更新时间:2024-01-20

我知道这很简单,可能在某些地方我不确定该寻找什么"类继承"?我正在尝试从货物中访问船的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;

原型的函数已经可以访问实例的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);

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

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);