var Test = (function() {
return {
someValue: 69,
staticMethod: function(){
return this.someValue;
}
}
}());
console.log(Test.staticMethod());
var doIt = Test.staticMethod
console.log(doIt())
输出:
69
undefined
预期:
69
69
<小时/>
为什么第二次调用的上下文中不存在this
?
最佳答案
doIt
引用了 staticMethod
所执行的相同函数:
function(){
return this.someValue;
}
this
基本上是 .
之前的对象
对于此调用:Test.staticMethod()
它是 Test
但是这里:doIt()
没有.
,所以点之前没有对象。
在这种情况下,this
被分配给全局对象(如果不是在严格模式下)。全局对象(浏览器中的window
)没有名为someValue
的属性,因此undefined
被注销。
关于javascript - 当调用设置为静态方法的变量时,这是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36802686/