在javascript中,如果对象A有一个属性是另一个对象B,我怎么能得到B中的A.

时间:2022-06-24 21:09:32
var A = {
    cc: 'opps',
    B: {
        dd: 'dd',
        getC: function () {
            return this.cc
        }
    }
}

how can i get cc ?? return A.cc in method getC or function () {return this.cc}.bind(this) or other way?

我怎么能得到cc?在方法getC或function(){return this.cc} .bind(this)或其他方式返回A.cc?

1 个解决方案

#1


If it's really a one-off object like that, just use A.cc:

如果它真的是一个像这样的一次性对象,只需使用A.cc:

var A = {
    cc: 'opps',
    B: {
        dd: 'dd',
        getC: function () {
            return A.cc;
        }
    }
};

If you have a constructor or builder producing these, then you'd have to do something in the constructor. It's hard to help you with that without an example, but for instance:

如果你有一个构造函数或构建器生成这些,那么你必须在构造函数中做一些事情。没有示例,很难帮助你,但例如:

// Constructor, used via new, e.g.: new Thingy()
function Thingy() {
    var t = this;
    t.cc = 'opps';
    t.B = {
        dd: 'dd',
        getC: function () {
            return t.cc;
        }
    };
}

// Builder, used without new, e.g.: createThingy()
function createThingy() {
    var A = {
        cc: 'opps',
        B: {
            dd: 'dd',
            getC: function () {
                return A.cc;
            }
        }
    };
    return A;
}

#1


If it's really a one-off object like that, just use A.cc:

如果它真的是一个像这样的一次性对象,只需使用A.cc:

var A = {
    cc: 'opps',
    B: {
        dd: 'dd',
        getC: function () {
            return A.cc;
        }
    }
};

If you have a constructor or builder producing these, then you'd have to do something in the constructor. It's hard to help you with that without an example, but for instance:

如果你有一个构造函数或构建器生成这些,那么你必须在构造函数中做一些事情。没有示例,很难帮助你,但例如:

// Constructor, used via new, e.g.: new Thingy()
function Thingy() {
    var t = this;
    t.cc = 'opps';
    t.B = {
        dd: 'dd',
        getC: function () {
            return t.cc;
        }
    };
}

// Builder, used without new, e.g.: createThingy()
function createThingy() {
    var A = {
        cc: 'opps',
        B: {
            dd: 'dd',
            getC: function () {
                return A.cc;
            }
        }
    };
    return A;
}