(function(){
var privateSomething = "Boom!";
var fn = function(){}
fn.addFunc = function(obj) {
alert('Yeah i can do this: '+privateSomething);
for(var i in obj) fn[i] = obj[i];
}
window.fn=fn;
})();
fn.addFunc({
whereAmI:function()
{
alert('Nope I\'ll get an error here: '+privateSomething);
}
});
fn.whereAmI();
Run Code Online (Sandbox Code Playgroud)
为什么whereAmI()无法访问privateSomething?以及如何将whereAmI()放在与addFunc()相同的上下文中?
Javascript 具有词法作用域:名称是指基于名称定义位置的变量,而不是使用名称的位置。privateSomething在 中作为本地查找whereAmI,然后在全局范围内查找。在这两个地方都找不到它。