我试图更好地理解JavaScript。
function foo() {
console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
当我尝试将其传递给函数时,会抛出错误。
function foo(this) {
console.log(this);
}
foo(); //Uncaught SyntaxError: Unexpected token this(…) on chrome console.
当我尝试传递指向窗口的变量时,我得到了未定义。
var that = this;
function foo(that) {
console.log(that):
}
foo(); // undefined chrome console.
我在上一个例子中期待窗口对象,就像我在控制台上输入窗口对象一样。
>>> that
window....
答案 0 :(得分:4)
this
上下文取决于函数的调用方式。请参阅What does "this" mean?。
this
会引用window
function foo() {
console.log(this);
}
foo();
此处,foo
是全局定义的函数,对foo()
的调用类似于window.foo()
,因此this
内的foo()
引用window
} object。
未捕获的SyntaxError:Chrome控制台上的这个(...)意外的标记。
function foo(this) {
console.log(this);
}
foo();
this
是保留关键字,不能用作标识符名称。另请注意,在调用函数时,没有参数传递给foo()
。
undefined
已在代码
var that = this; // Global that
function foo(that) { // Parameter `that`
console.log(that); // <-- Use semicolon here
}
foo(); // `that` is not passed.
因为that
作为参数传递给全局that
遮盖了阴影。由于没有任何内容传递给foo()
,因此会记录undefined
。
答案 1 :(得分:1)
var that = this;
function foo(that){
console.log(that):
}
foo();
foo()
参数缺失。
所以function foo(that)
将是undefined
。
让它发挥作用
foo(that)
答案 2 :(得分:0)
function foo(this) {
console.log(this);
}
foo(); //Uncaught SyntaxError: Unexpected token this(…) on chrome console.
在这种情况下,调用不会设置此值。由于代码不是严格模式,因此其值必须始终为对象,因此默认为全局对象。
function foo(this) {
console.log(this);
}
foo(); //Uncaught SyntaxError: Unexpected token this(…) on chrome console.
在这种情况下,使用参数定义foo函数,然后调用它而不带任何值。 在函数内部,该值的值不是由调用设置的。由于代码不是严格模式,因此其值必须始终为对象,因此默认为全局对象。
var that = this;
function foo(that){
console.log(that); //<-here is semicolon ';'
}
foo(); // undefined chrome console.
如果你理解上面提到的两个案例可能会理解这里发生的事情。有关详细信息,请查看:mdn-js-this
答案 3 :(得分:0)
此指的是Javascript中当前执行的上下文。这个上下文是Javascript保留给自己的东西,它是readonly。您只能读取该上下文中可用的变量。你无法覆盖它。 当你做这样的事情时:
function foo(this){
console.log(this);
}
foo();
在函数中使用参数 this ,您试图覆盖当前不允许的上下文,因此您会收到错误。
并且,当您运行此代码时:
var that = this;
function foo(that){
console.log(that):
}
foo();
调用foo函数时没有传递任何参数,因此的值未定义。请注意,在此foo函数上下文中,此的早期分配 将被覆盖。