繁体   English   中英

JavaScript:嵌套对象值可以引用其父对象键吗?

[英]JavaScript: Can a nested object value reference its parent object key?

我有一个对象,如下所示:

var obj = {
    parentKey : {
        nestedKey1 : value, 
        nestedKey2 : function () {
            return parentKey + nestedKey2;
        }
    }
};

有没有一种方法可以使用上述嵌套键值对之一中的函数中parentKeynestedKey1和/或nestedKey2的实际名称中的值?

在我的实际场景中, keys都是我希望用作for loop标准的所有数值。


更新方案到问题

作为学习JavaScript的练习,我决定对电梯系统的逻辑进行编码。 为此,我制作了一个代表建筑物的对象,该对象包含每个楼层,嵌套在每个楼层中的是希望前往另一个楼层的人数数据,如下所示:

var floorData = {
    <floor number> : {
        <people going to floor X> : <number of people>,
        <people going to floor Y> : <number of people>,
        peopleGoingUp : <formula that sums amount of people going up>,
        peopleGoingDown : <formula that sums amount of people going down>
    }
};

我想在每个<floor number>对象中包括一个属性,该属性通过公式求和peopleGoingUppeopleGoingDown的数量。 为了使此公式按我的peopleGoingUp工作,我需要访问<floor number>名称,该名称是来自peopleGoingUppeopleGoingDown公式中的数字值。

到目前为止,这是我的工作示例,并且在theBuilding[2]地板中包含了peopleGoingUppeopleGoingDown公式。 我希望的是将theParentKey的手动输入值theParentKey为等于父对象的名称。

// Total number of floors in building global object
var totalFloors = 3;

// Building object including amount of people waiting to take lift to other floors on each level of the building
var theBuilding = {
    0 : {
        1 : 2,
        2 : 0,
        3 : 1,
    },
    1 : {
        0 : 1,
        2 : 3,
        3 : 2,
    },
    2: {
        0 : 2,
        1 : 1,
        3 : 4,
        goingUp : function () {
            var sum = 0;
            var theParentKey = 2; // this is supposed to be a direct reference to the parent object name to this nested object and thus equal to 2
            for (i = 0; i <= totalFloors; i++) { // loop for total floors 
                if (i !== theParentKey && i >= theParentKey) {//sum if i isn't = this floor number and that i is greater than this floor number
                    sum += this[i]
                }
            };
            return sum;
        },
        goingDown : function () {
            var sum = 0;
            var theParentKey = 2; // this is supposed to be a direct reference to the parent object name to this nested object and thus equal to 2
            for (i = 0; i <= totalFloors; i++) { // loop for total floors from lowest
                if (i !== theParentKey && i <= theParentKey) { //sum if i isn't = this floor number and that i is less than this floor number
                    sum += this[i]
                }
            };
            return sum;
    },
    3 : {
        0 : 0,
        1 : 1,
        2 : 4
    }
};

console.log(theBuilding[2].goingUp()); // 4
console.log(theBuilding[2].goingDown()); // 3

如果我理解您的问题,则想获取键的名称。 您可以在传递当前对象this同时使用Object.keys()

var obj = {
    parentKey : {
        nestedKey1: 3, 
        nestedKey2: function () {
            return Object.keys(this);
        }
    }
};

console.log(obj.parentKey.nestedKey2()); // ['nestedKey1', 'nestedKey2']

看到这是一个例子

 var obj = { parentKey : { nestedKey1 : "value", nestedKey2 : function () { var c = obj.parentKey; //console.log("we get "+ c.nestedKey1 +" & "+ c.nestedKey3); //you can update values //obj.parentKey.nestedKey1 = "new value"; console.log("we get "+ c.nestedKey1 +" & "+ c.nestedKey3); return "we get "+ c.nestedKey1 +" & "+ c.nestedKey3; }, nestedKey3 : "another value" } }; obj.parentKey.nestedKey2(); var an = window["obj"]["parentKey"]["nestedKey3"]; console.log(an); 

有没有一种方法可以使用上述嵌套键值对之一中的函数中parentKey和nestedKey1和/或nestedKey2的实际名称中的值?

您可以通过两种方式来实现。

使用词法范围

nestedKey2内部的函数可以访问全局范围。 因此,您可以使用来访问obj每个属性.

obj.Parentkey

使用this

这是比较麻烦一些,因为this在多目标函数内部将指向作为函数驻留在对象的“同一级别”。您可以使用this一起. 达到物体的较低水平,但无法达到较高的水平。

但是,您可以使用变通方法来实现循环引用

var myObj = {

    levelAccess: function() {
        this.two.__ = this;
        return this;
        },

    one: 'one',
    two: 
        {
        __: [],

        myFunction: function () {return this.__.one}
        }

    }.levelAccess();

此解决方案要求您为需要访问更高级别的每个级别添加一个__属性,然后通过levelAccess函数初始化所有__属性。 该解决方案不应引起任何内存泄漏,请参阅

暂无
暂无

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

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