从子类访问javascript父类属性 [英] access javascript parent class properties from subclass

查看:78
本文介绍了从子类访问javascript父类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好我在javascript中有一个关于obj的问题
如何访问父类属性

hi guys I had a question about obj in javascript how can I access parent class properties

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?
任何人都可以帮忙?

it seems 'this' in 'changeParentClassName' is subObj, how can I access parentclass.name ? anyone can help ??

推荐答案

JavaScript的将调用函数时,它是左侧的对象。在这种情况下,subObj不是parentObj,因此您在subObj上设置 name 。你有2个选项,你可以把这个放在 generate 里面的另一个变量中,这样它就不会被JavaScript取代逻辑。类似于:

JavaScript's this will be the object to the left of the . when calling the function. In this case, it is the subObj not the parentObj so you are setting name on subObj. You have 2 options, you can put this in a different variable inside generate so it doesn't get replaced by JavaScript's this logic. Something like:

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

或者您可以使用bind()创建一个具有这个绑定到一个已知对象(在本例中是你的父对象)类似于:

Or you can use the bind() to create a new function that will have this bound to a known object (in this case your parent object) Something like:

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()获取有关绑定和交互式示例的更多信息。

Check out Function bind() for more info on bind and interactive examples.

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

Note, if you are targeting a recent version of Javascript (ECMAScript 6 or later), you can use a => function which does not change the value of this compared to the declaring scope. So you could use:

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

这篇关于从子类访问javascript父类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆