1.使用场景
- 构造函数
- 对象属性
- 普通函数、
- call apply bind
- ========================================上述this只有在执行的时候才能确定,定义时无法确定
- 嵌套函数
- 箭头函数
- 匿名函数、setTimeout/setInterval
2.实例
- 构造函数
function Fn1(name){
this.name=name;
};
Fn1.prototype.hobby=function(){
alert(1)
};
var a = new Fn1("duliz");
- 对象属性
-
普通函数var b=1; var a={ b:2, c:function(){ alert(this.b) } }; a.c();//2 var fn=a.c; fn();//1
- call apply bind
function a4(m){ console.log(this) console.log(m) }; a4.call({},"duliz");//window a4.apply({},["duliz"]); var b4=function (){ console.log(this) }.bind({}); b4(); var e4=a4; F4=e4.bind({}); F4() function a4(m){ console.log(this) console.log(m) }; a4.call({},"duliz");//window a4.apply({},["duliz"]); var b4=function (){ console.log(this) }.bind({}); b4(); var e4=a4; F4=e4.bind({}); F4()
- 嵌套函数(在嵌套函数中:和变量不同,this关键字没有作用域的限制。JavaScript对于全局函数内的this绑定为全局对象,而对于嵌套函数也采用了相同的解释)
var me = { name : 'Jimbor', blog : 'http://jmedia.cn/', sayMyName : function(){ var pre = 'My name is: '; function displayName(){ alert(pre + this.name); } displayName.apply(me); // displayName() } } me.sayMyName();
- 箭头函数(箭头函数内部的
this
是词法作用域,由上下文确定,就是定义时所在的对象,而不是使用时所在的对象)上面的例子就可以使用箭头函数矫正 var me = { name : 'Jimbor', blog : 'http://jmedia.cn/', sayMyName : function(){ var pre = 'My name is: '; var displayName=()=>{ alert(pre+this.name)}; displayName() } } me.sayMyName();
function foo() { setTimeout(() => { console.log('id:', this.id); }, 100); } var id = 21; foo.call({ id: 42 }); // id: 42
- 匿名函数、setTimeout/setInterval函数都指向window
function a6(){ var b6=1; (function(){ console.log(this) })(); }; a6.call({})
function a7(){ var b7=1; setTimeout(function(){ console.log(this);//window console.log(b7)//1 },100) }; a7.call({})