javascript call 方法中的 "this"对象

标签 javascript

我创建这些函数是为了检查每个函数中的“this”是什么,并且想知道当使用调用函数时,为什么“this”不是“测试”对象?

function foo() {
        console.log("call foo:", this);
        bar();
    }

function bar() {
    //why the "this" is not the "test" object
    console.log("call bar:", this);
}

function Test() {

}

var test = new Test();
foo.call(test);

最佳答案

如果你这样做foo.call(test) ,然后在 foo() 内, this将是test .

但是,在 foo() 里面,当您调用bar()时,this然后值将在 bar() 内重置为其默认值。

Javascript 中的每个函数调用都会设置一个新值 this根据函数的调用方式。

简单的函数调用,例如 bar() ,设置 this 的值如果未在严格模式下运行,则为全局对象,或者为 undefined如果运行严格模式。

回顾一下设置 this 的方法对特定事物的值(value)是:

foo.call(test, ...);      // sets this to test
foo.apply(test, ...);     // sets this to test

obj.method();             // sets this to obj

var x = foo.bind(test);   
x();                      // sets this to test

var x = new foo();        // create a new object and sets this to the new object

foo();                    // this set to global object or undefined (in strict mode)
<小时/>

只要记住 this 的值即可根据上述规则,Javascript 中的每个函数调用都会重置。它永远不会从以前的值“继承”。每次函数调用时,它总是根据函数调用的方式设置为新的值。对于刚接触 Javascript 的人来说,这是一个常见的误解(很多个月前我就被同样的事情绊倒了)。

还值得注意的是,回调函数的值可能为 this调用回调函数时设置为特定内容(内部使用 . apply().call() )。例如:

function submitHandler(e) {
   // value of this is in this function is set
   // by addEventListener to the DOM object that handled the event
}

document.getElementById("submit").addEventListener("click", submitHandler);
<小时/>

有关该主题的其他引用:

When you pass 'this' as an argument

A Better Understanding of This

How does the "this" keyword work?

关于javascript call 方法中的 "this"对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28313046/

相关文章:

javascript - 在输入文本js上显示数组结果

javascript - JQuery 检查输入是否为空而不检查加载?

javascript - 如何更改我的输入类型范围的缩略图颜色?

javascript - "JavaScript: The Good Parts"- 为什么 delete 可以用作属性名称,而书中暗示它不应该

检测第三方cookie是否被禁用的JavaScript解决方案

javascript - 根据选定的值启用按钮

javascript - Parse.com Javascript API,查询包含指针列表的对象列表

JavaScript - 递归函数中的错误是什么?

javascript - Ui.Router使用lazyLoad导入JS文件,但按钮失去功能

javascript - jQuery 获取上下文?