我创建这些函数是为了检查每个函数中的“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
关于javascript call 方法中的 "this"对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28313046/