匿名函数中的this在没有明确挂载的时候具有全局性,指向window,如果是"use strict"模式下,this没有确定的挂载的话,则为undefined(如有错误,请指出,谢谢!)
但是在有明确指向时,则指向挂载对象(使用了bind(),call(),apply())
1.指向window.下面例子,非"use strict"模式
var x = 20;
var obj = {
x : 15,
fn:function(){
return function(){
console.log(`this is :${this}`);
return this.x;
}
}
}
var temp = {x:33};
console.log(obj.fn()()); //20 this is window
console.log(obj.fn().call(temp)); // 33 this is temp 挂载在了temp上
2.为了让匿名函数不指向window或者挂载对象,可以在函数上一层把this指向想要的target
var x = 20;
var obj = {
x : 15,
fn:function(){
let self = this;//关键代码
return function(){
console.log(`this is :${this}`);
return self.x;
}
}
}
var temp = {x:33};
console.log(obj.fn()()); //15 this is window
console.log(obj.fn().call(temp)); // 15 this is temp
3.没有挂载的独立函数也类似匿名函数,this指向window
var length = 10;
function fn() {
console.log(this.length);
}
var obj = {
length: 5,
method: function(fn) {
fn();//没有挂载,this和匿名韩式一样指向window
}
}
obj.method(fn)//10