【发布时间】:2019-02-26 05:49:31
【问题描述】:
为什么在以下示例中结果的值是“未定义”?请解释一下这是如何计算的?
<script>
var foo = {
bar: function() { return this.baz; },
baz: 1
};
var a = (function(){
return typeof arguments[0]();
})(foo.bar);
console.log(a);
</script>
注意:我已经通过以下链接,它没有解释这一点 例子。这里没有构造函数... How to access the correct `this` inside a callback?
【问题讨论】:
-
不要发布同样的问题over again - 这确实是对那个规范的欺骗。
arguments[0]()在没有调用上下文的情况下调用arguments[0]中的任何函数。就像我在对该问题的评论中所说的那样,要保留调用上下文,请传递() => foo.bar()或使用.bind -
@CertainPerformance How does the “this” keyword work? 将是一个更好的欺骗目标,恕我直言...
-
thisinbar指的是arguments的a对象,当您调用bar时,例如来自a的arguments[0]()。请注意,arguments是一个对象,而不是一个数组。见a fiddle。 -
使用此代码
return typeof ( arguments[0].call(foo) );
标签: javascript html function