我正在尝试更好地理解 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....
最佳答案
JavaScript 中的
this
上下文取决于函数的调用方式。请参阅What does "this" mean? .
this
将引用window
function foo() { console.log(this); } foo();
这里,
foo
是全局定义的函数,对foo()
的调用就像window.foo()
,因此foo()
内的 thiswindow
对象。未捕获的语法错误:Chrome 控制台上出现意外的标记 this(...)。
function foo(this) { console.log(this); } foo();
this
是保留关键字,不能用作标识符名称。另请注意,调用该函数时,没有参数传递给foo()
。未定义
在下面的代码中登录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
。
关于javascript - 将 this 传递给函数的基本查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36324220/