关于this
this
fn()
this => window/global
obj.fn()
this => obj
fn.call(xx)
this => xx
fn.apply(xx)
this => xx
fn.bind(xx)
this => xx
new Fn()
this => 新的对象
fn = ()=> {}
this => 外面的 this
案例
javascript
var length = 4;
function callback() {
console.log(this.length); // => 打印出什么?
} // this指向外面的window,var length = 4 会被挂载到全局上
const obj = {
length: 5,
method(callback) {
callback(); // callback.call(undefined)
}
};
obj.method(callback, 1, 2);
call、apply、bind
call
call
方法使用一个指定的this
值和单独给出的一个或多个参数来调用一个函数。javascriptfunction add(a, b) { return a + b; } add.call(this, 1, 2) // 3
apply
apply
方法和call
方法类似,但是可以接受一个含多参数的数组。javascriptfunction f(x, y){ console.log(x + y); } f.call(null, 1, 1) // 2 f.apply(null, [1, 1]) // 2
bind
bind
方法用于将函数体内的this
绑定到某个对象,然后返回一个新函数。javascriptvar counter = { count: 0, add: function () { this.count++; } }; var otherCounter = { count: 999 } var func = counter.add.bind(counter); counter.count // 0 func(); counter.count // 1 var funcOther = counter.add.bind(otherCounter); funcOther(); otherCounter.count // 1000