为什么“;这个“;在JavaScript中被称为隐式参数

Why is "this" in JavaScript said to be an implicit parameter?

本文关键字:参数 被称为 JavaScript 这个 为什么      更新时间:2023-09-26

我想知道为什么在John Resig的《JavaScript忍者的秘密》一书中,第48页说:

每当调用函数时。。。一个名为this的隐式参数也传递给函数。

我有点困惑,因为之前我读到this实际上是一个关键词。也许这并不重要,除非我们尝试

function f() {
    this = {};
}
f();

则Chrome或Node.js都会引发一个错误,即它是赋值中的无效左侧。所以,如果this实际上是一个隐式参数,那么这一行不应该引发错误吗?所以我想知道这本书对this有这个错误是真的吗?

更新:我还重新检查了JavaScript:the Definition Guide 6th Edition和ECMA-262,他们都说this是一个关键字)。。。

这确实是一个隐含的参数,因为如果您编写:

var foo = {
    bar: function() {
        console.log(this);  // Will be foo.
    }
};
foo.bar();

thisbar()内隐式绑定到foo,就好像您显式编写了:

foo.bar.call(foo);
function foo(explicitVar /*, this */ ) {
}
// this will only be defined when foo is called
// default: this == window
// directly invoking a function will bind this to `window`
foo(1 /*, window */) // explicitVar == 1, this == window (inside foo)
var a = {
    fuu: foo
}
// invoking foo ON another object binds this to that object
a.fuu(2 /*, a */) // explicitVar == 2, this == a (inside a.fuu)
// even when you reuse a function that was assigned to another object,
// the this will only be bound when invoking
bar = a.fuu
bar(3 /*, window */) // explicitVar == 3, this == window (inside bar)

从这些例子中,您可以看到,为了解释this,您可以将其描述为具有特殊执行语义的神奇关键字,也可以将其解释为隐式参数,因为它只有在某些上下文中调用函数时才会被赋值。

两者兼而有之!

它是一个隐式参数,因为它不是函数声明的一部分,例如

function foo()
{
    // this === window
}
foo();

然而,由于JavaScript执行foo():的方式,它和其他对象引用一样存在

foo.call(window)

但从某种意义上说,它也是一个关键字,因为它受某些规则的控制,例如不能为其赋值。

实际上,这是同一概念的两个维度。

关键字'this'=>它用于用户识别不应用作函数或变量名的字符串。

隐式参数'this'=>这是javascript引擎识别该对象的一种方式,而该对象又由您和用户抽象,例如

  this.name //I don't care about which object. It is taken care of 

而不是将自己与混淆

  obj1.name // or is it, obj2 !!! ?? 

在这里,"小心"部分成为用户的关键字,也是javascript引擎的隐式参数,这样它就可以为您提供抽象。