我知道这很简单,而且可能在某些地方我不确定要寻找什么“类继承”?我正在尝试从 cargo 内部访问船舶的 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;
最佳答案
原型(prototype)函数已经可以访问实例的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);
关于javascript - 从继承类访问父级 "this"变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20336310/