JavaScript访问父对象属性 [英] JavaScript access parent object attribute

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

问题描述

我在JS中有一个小问题,我有两个嵌套对象,我想从父级访问变量,如下所示:

I have a small issue in JS, I have two nested objects, and I would like to access a variable from the parent, like so:

var parent = {
    a : 5,

    child: {
        b : 3,
        displayA : function(){
            console.log(this.a);
            //undefined
            },

        displayB : function(){
            console.log(this.b);
            //displays 3
            }
        }
}

我只想知道如何使parent.child.displayA起作用:)(我有一些需要访问父变量的子对象)

And I would just like to know how to make parent.child.displayA work :) (I have sub-objects that need access to a parent's variable)

任何帮助表示赞赏 非常感谢你!

Any help appreciated Thank you very much!

推荐答案

您可以使用您可能还对绑定感兴趣:

parent.child.displayA = function(){
  console.log(this.a);
}.bind(parent);
parent.child.displayA(); // 5

或者您也可以只使用parent代替this:

Or you you can just use parent instead of this:

parent.child.displayA = function(){
  console.log(parent.a);
};
parent.child.displayA(); // 5

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

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