在解释箭头功能时,w3schools说:“在常规功能中,此关键字代表调用该函数的对象,可以是窗口,文档,按钮或其他任何东西”,而“在常规功能中,此关键字代表具有以下功能的对象:调用函数”。链接:https://www.w3schools.com/js/js_arrow_function.asp
I'm trying to understand this sentence, not in relation to arrow functions but by itself. It seems that many other sources I found on the net contradict to this, saying that when a function gets called on its own (not as a method), 'this' gets bound to either the toplevel object (e.g. window) or undefined, depending on strict mode.
So I built a simple example (running non-strict in the browser). I did not want to use the examples from the w3schools site because they use event handlers for explanation, and I want to make sure that I avoid any additional binding logic that event handlers introduce.
<script type="text/javascript">
function foo() {
console.log('foo on ' + this.prop);
}
function bar() {
console.log('bar on ' + this.prop);
var f = this.foo;
f();
}
var x = {
prop: 'x'
};
window.prop = 'w';
x.foo = foo;
x.bar = bar;
x.bar();
</script>
This logs: "bar on x" and "foo on w", which seems to indicate that in foo, this refers to the window. So obviously the w3schools explanation does NOT refer to an automatic binding of foo's this to bar's this when foo gets called inside bar. But what else does it mean?
Well, let's start with the premise that W3Schools has a less than stellar reputation and you shouldn't be thinking too hard about whatever it is they're writing. In fact, you should preferably read MDN instead.
In regular functions the this keyword represented the object that called the function...
好吧,是的,不…… 一个对象什么也没叫。一个对象就是。这是其他东西的容器。这样的“东西”可以是一种功能。然后,您可以有代码这需要的功能从“容器”,并调用它。因此,代码会调用函数,无论这些函数是对象的属性还是其他属性。
如何this
确定内部的功能依赖于准确的代码如何调用该函数。简而言之,在表达式中a.b()
,this
内部b
将是a
。通常,this
函数内部将.
是调用该函数之前的所有内容。
如果.
在调用之前b()
没有this
(例如),则没有(它的显示方式完全取决于严格模式)。该函数最初是否是对象的一部分并不重要;重要的是用于调用它的确切表达式。
有关所有细节,您可以查看“ this”关键字如何工作?。
这里的脚注是您可以使用或在函数上或显式传递另一个函数,而胖箭头函数完全不遵循此规则。bind
this
this
call
apply
使用您链接到的另一个问题的术语:假设未使用bind()绑定的(非箭头)函数被直接调用(而不是通过调用或应用),并且不带点被调用。在严格或非严格模式下,是否有新执行上下文的thisBinding设置为调用执行上下文的thisBinding的情况?并不是说它们恰好是相同的情况,例如当“ this”是两者中的顶级对象(窗口)时。IOW,是否存在这样的调用会终止func.call(this,...)?
我不知道,不。
this
调用方范围内的值永远不会自动从调用方的函数继承。这就是=>
发明功能的原因,因为这是一个普通的用例,原始规范中没有直接解决。这实际上不是问题的一部分,而是为了避免使阅读此内容的任何人感到困惑:AFAIK箭头函数从其定义的位置(词法闭包)而不是从调用函数的位置继承“ this”。无论如何,对该问题的实际答案似乎是w3schools在这里根本是错误的。