在下面的示例中,当调用functionA()时,this关键字引用了包含的对象,因此我可以访问其属性(例如theValue)

我的问题:我如何从嵌套的myObj中引用functionB()的属性?

var myObj = {
    theValue: "The rain in Spain",
    functionA: function() {
        alert(this.theValue);
    },
    moreFunctions: {
        functionB: function() {
            alert(????.theValue);
        }
    }
}

myObj.functionA();
myObj.moreFunctions.functionB();

提前致谢。

最佳答案

立即援救!

var myObj = (function () {
    var that = {
        theValue: "The rain in Spain",
        functionA: function() {
            alert(this.theValue); // or that.theValue, both work here
        },
        moreFunctions: {
            functionB: function() {
                alert(that.theValue);
            }
        }
    };
    return that;
}()); // <-- immediate invocation !!

您可以进一步分解它:
var myObj = (function () {
    function functionA() {
        alert(that.theValue);
    }
    function functionB() {
        alert(that.theValue);
    }
    var that = {
        theValue: "The rain in Spain",
        functionA: functionA,
        moreFunctions: {
            functionB: functionB
        }
    }
    return that;
}());

如果您熟悉OOP,则可以使用它来创建私有(private)变量。

10-07 15:54