【问题标题】:Kindly explain why in following example the output is 'undefined'? [duplicate]请解释为什么在以下示例中输出为“未定义”? [复制]
【发布时间】: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] 中的任何函数。就像我在对该问题的评论中所说的那样,要保留调用上下文,请传递 () =&gt; foo.bar() 或使用 .bind
  • @CertainPerformance How does the “this” keyword work? 将是一个更好的欺骗目标,恕我直言...
  • this in bar 指的是argumentsa 对象,当您调用bar 时,例如来自aarguments[0]()。请注意,arguments 是一个对象,而不是一个数组。见a fiddle
  • 使用此代码return typeof ( arguments[0].call(foo) );

标签: javascript html function


【解决方案1】:

arguments[0]()Window 上下文中执行,但它没有在名称 bar 中定义任何对象属性(这是 foo 的属性) .这就是你得到undefined 的原因。要解决这个问题,您可以绑定对象。

改变

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);

【讨论】:

  • “请解释为什么要关注...”
  • 你能告诉这里的arguments[0]是什么意思吗?要么 -- foo.bar 或返回值 '1'?还是什么?
  • @Deadpool, arguments[0] 指的是您传递给函数的函数。
  • @Mamun - 它指的是我们在函数中传递的函数或参数??? (就像我们在 foo.bar 中传递 name、age 作为参数???)
  • @Deadpool,它会将您传递给函数的内容作为参数引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 2014-11-20
  • 1970-01-01
  • 2016-07-06
  • 2023-04-02
  • 1970-01-01
  • 2020-10-04
相关资源
最近更新 更多