javascript - 从继承类访问父级 "this"变量

标签 javascript class inheritance

我知道这很简单,而且可能在某些地方我不确定要寻找什么“类继承”?我正在尝试从 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/

相关文章:

matlab - 如何取消父类(super class)对默认 Matlab 函数的覆盖

javascript - Jquery 调整 li 大小以适应 ul

javascript - Webdriver IO 中的帧处理

javascript - Kendo MVC Chart - 渲染事件问题

python - Flask 应用程序中的类导入出现问题

javascript - 使用RequireJS : should I define inherited resources

具有继承的字段的 c# 类设计

javascript - 如何阻止切换更改侧导航栏的宽度?

python - 在 Python 中装饰实例方法

c++ - 构造函数不一致的多级类继承