执行此代码块时,将显示未定义,而不是“Vasya”,因为 setTimeout 接收到 user.sayHi 方法,但不是其上下文:
var user = {
firstName: "Вася",
sayHi: function() {
alert( this.firstName );
}
};
setTimeout(user.sayHi, 1000); // undefined (не Вася!)
如果方法调用包含在匿名函数中,则会显示“Vasya”。
setTimeout(function() {
user.sayHi(); // Вася
}, 1000);
其实问题来了:为什么在匿名函数中包装方法调用时会出现context?
如果不将它包装在匿名函数中,它就变成了窗口。
通过包装,这等于对象:
您可以通过 func.call(context, arg1, arg2...) 调用函数来手动设置它
问题是只有函数本身被传递给 setTimeout 回调,没有它的上下文。
使用
bind;上下文更改只是因为上下文等于(在 bind 案例之外)到被调用函数之前写的内容。
如果点之前没有任何东西,那么到全局对象或者
undefined在这种情况下"use strict";