2017-06-22 78 views
2

我是javascript新手,根据我对javascript的了解,下面的问题应该返回1,但它返回“undefined”。 谁能告诉我为什么它不返回1?为什么它返回“undefined”而不是1

var foo = { 
    bar: function() { return this.baz; }, 
    baz: 1 
    }; 
    (function(){ 
    return typeof arguments[0](); 
    })(foo.bar); 
+1

因为foo.bar内的'this'是指全局对象。没有全局变量'baz'因此'this.baz'是'undefined'。详细了解'this'如何在这里工作:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this,[“this”关键字如何工作?](https: //stackoverflow.com/q/3127429/218196)。此外,它永远不会返回'1',因为['typeof'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)返回*的类型*值。 '1'不是一种类型。 –

+0

“应该返回1”,否。如果'this'是'foo',它'应该'返回''number'':'返回typeof参数[0] .apply(foo);' – Arg0n

+0

参见[如何在回调中访问正确的'this'上下文?](https://stackoverflow.com/q/20279484/218196) –

回答

5

当调用一个函数.运算符,则该对象的.左侧成为调用的上下文中,这是this。但是当你将你的函数作为参数传递给另一个函数时,由于你直接调用它,你会失去上下文。如果你想保留上下文,你可以使用bind

(function(){ 
    return typeof arguments[0](); 
})(foo.bar.bind(foo)); 

而且,是的,你的函数实际上返回的baz类型,而不是本身的价值。如果您想查看1,请删除typeof

1

为什么它返回“不确定”,而不是1

因为你调用函数的方式,thisfoo.bar全局对象(即window)。没有全球变量baz因此this.bazwindow.baz)是undefined
详细了解如何在这里this作品:


此外,它也绝对不会返回1因为typeof返回值的类型1不是一种类型。充其量它会返回"number"

console.log(typeof 1); 
 
console.log(typeof undefined);

要了解如何控制this值,看看上面和How to access the correct `this` context inside a callback?的链接。