2

我有一个关于 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?

4

1 回答 1

7

JavaScriptthis将是.调用函数时左侧的对象。在这种情况下,它是 subObj 而不是 parentObj,因此您name在 subObj 上进行设置。你有 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

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

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

this.subObj.changeParentClassName = () => // button obj wants to change name
{
    this.name = "not parent";
};
于 2013-10-23T02:38:43.843 回答