[英]why its returning the “undefined” instead of 1
I am new to javascript, The below question should return 1 according to my knowledge about javascript, but it's returning "undefined". 我是javascript新手,根据我对javascript的了解,以下问题应返回1,但返回的是“ undefined”。 could anyone tell me why it's not returning 1?
谁能告诉我为什么它不返回1?
var foo = {
bar: function() { return this.baz; },
baz: 1
};
(function(){
return typeof arguments[0]();
})(foo.bar);
When you invoke a function with .
当您使用调用函数时
.
operator, then the object to the left of .
运算符,然后是左侧的对象
.
becomes the context of invocation, which is this
. 成为调用的上下文,也就是
this
。 But when you pass your function to another one as an argument, you lose the context, since you call it directly. 但是,当您将函数作为参数传递给另一个函数时,会丢失上下文,因为您直接调用它。 If you want to preserve the context you can use
bind
. 如果要保留上下文,可以使用
bind
。
(function(){
return typeof arguments[0]();
})(foo.bar.bind(foo));
And, yeah, your function actually returns the type of baz
, not the value itself. 而且,是的,您的函数实际上返回
baz
的类型,而不是值本身。 Remove typeof
if you want to see 1
. 删除
typeof
如果你想看到1
。
why its returning the “undefined” instead of 1
为什么它返回的是“ undefined”而不是1
Because the way you call the function, this
inside foo.bar
refers to the global object (ie window
). 因为调用函数的方式,
this
foo.bar
中的此对象引用全局对象 (即window
)。 There is no global variable baz
hence this.baz
( window.baz
) is undefined
. 没有全局变量
baz
因此this.baz
( window.baz
)是undefined
。
Learn more about how this
works here: 在此处了解有关
this
工作原理的更多信息:
Besides, it would never ever return 1
because typeof
returns the type of a value. 此外,它永远不会返回
1
因为typeof
返回值的类型 。 1
is not a type. 1
不是类型。 At best it would return "number"
: 充其量只能返回
"number"
:
console.log(typeof 1); console.log(typeof undefined);
To learn how to control the value of this
, have a look at the links above and at How to access the correct `this` context inside a callback? 要了解如何控制
this
的值,请查看上面的链接以及如何在回调中访问正确的`this`上下文? . 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.