javascript - 将 this 传递给函数的基本查询

标签 javascript

我正在尝试更好地理解 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? .

  1. this 将引用 window

    function foo() {
        console.log(this);
    }
    foo();
    

    这里,foo是全局定义的函数,对foo()的调用就像window.foo(),因此 foo() 内的 this 引用 window 对象。

  2. 未捕获的语法错误:Chrome 控制台上出现意外的标记 this(...)。

    function foo(this) {
        console.log(this);
    }
    foo();
    

    this 是保留关键字,不能用作标识符名称。另请注意,调用该函数时,没有参数传递给 foo()

  3. 未定义在下面的代码中登录

    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/

相关文章:

javascript - Android 视频插件 Phonegap with Cordova 2.2.0

javascript - Canvas drawImage 使用数据 URL

javascript - Eloquent Javascript LifeLikeTerrarium 克隆

javascript - WordPress。联系表单 7. 如果另一个字段的值 > 0,则设置必填字段

javascript - 从javascript中的按钮检索名称值

javascript - 数组 null 在 JavaScript 中不验证

javascript - 显示触发的 JavaScript 事件

javascript - 使用脚本标签 Block 制作 Javascript document.write

javascript - 在不使用 "this"的情况下引用 "this"

javascript - 从输入中展平嵌套数组