请解释为什么在以下示例中输出为“未定义"? [英] Kindly explain why in following example the output is 'undefined'?

查看:51
本文介绍了请解释为什么在以下示例中输出为“未定义"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下示例中,为什么结果的值是'undefined'?请解释一下这是如何计算的?

Why the value of outcome is 'undefined' in the following example? Kindly explain someone how is this calculated?

<script>
var foo = {
  bar: function() { return this.baz; },
  baz: 1
};

var a = (function(){
  return typeof arguments[0]();
})(foo.bar);

console.log(a);
</script>

注意:我已经浏览了以下链接,但并没有对此进行解释例子.这里没有构造函数...如何在回调中访问正确的`this`?

推荐答案

参数[0]()

arguments[0]() is executing in the Window context, but it does not have any object property defined in the name bar (which is a property of foo). This is why you get undefined. To solve the issue, you can bind the object.

更改

foo.bar

收件人

foo.bar.bind(foo)

var foo = {
  bar: function() { return this.baz; },
  baz: 1
};
var a = (function(){
  console.log(this.constructor.name); // Window
  return typeof arguments[0]();
})(foo.bar.bind(foo));

console.log(a);

这篇关于请解释为什么在以下示例中输出为“未定义"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆