繁体   English   中英

如何从子类访问父类属性?

[英]How to access the parent class properties from a subclass?

我有一个关于 Javascript 对象的问题。 如何访问父类的属性?

function randomObj() // for example button obj
{
    this.text = "this is obj";
}

function parentClass()
{
    this.name = "parent";
    this.subObj;
}

parentClass.prototype.generate = function()
{
    this.subObj = new randomObj();
    this.subObj.changeParentClassName = function() // button obj wants to change name
    {
        this.name = "not parent";
    }
}

var sampleObj = new parentClass();
sampleObj.generate();
sampleObj.subObj.changeParentClassName (); // does not works

'changeParentClassName' 中的 'this' 似乎是 subObj,我如何访问 parentclass.name?

JavaScript 的this将是. 调用函数时。 在这种情况下,它是 subObj 而不是 parentObj,因此您在 subObj 上设置name 您有 2 个选项,您可以将this放在generate中的不同变量中,这样它就不会被 JavaScript 的this逻辑替换。 类似的东西:

var parentObj = this;
this.subObj.changeParentClassName = function() // button obj wants to change name
{
    parentObj.name = "not parent";
};

或者您可以使用 bind() 创建一个新函数, this函数将绑定到一个已知对象(在这种情况下是您的父对象),例如:

this.subObj.changeParentClassName = (function() // button obj wants to change name
{
    this.name = "not parent";
}).bind(this); // bind the 'this' inside the changeParentClassName to the 'this' inside generate

查看函数 bind()以获取有关绑定和交互式示例的更多信息。

请注意,如果您的目标是最新版本的 Javascript(ECMAScript 6 或更高版本),您可以使用=>函数,该函数与声明范围相比不会更改this的值。 所以你可以使用:

this.subObj.changeParentClassName = () => // button obj wants to change name
{
    this.name = "not parent";
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM