温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - What does "With a regular function 'this' represents the object that calls the function" mean?

javascript - “使用常规函数'this'表示调用该函数的对象”是什么意思?

发布于 2020-03-28 23:33:18

在解释箭头功能时,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?

查看更多

查看更多

提问者
Martin Geisse
被浏览
55
2020-01-31 17:57

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 thisthiscallapply

发布
问题

分享
好友

手机
浏览

扫码手机浏览