javascript非严格模式下this的用法

作者:日期:2017-03-05 22:44:47 点击:248

this的用法

========

周末班:王艺霏

1. 绑定事件函数中的this


只有当事件被触发的时刻,才知道this是谁,谁(DOM元素)触发该事件,谁就是该事件函数中的this。 
例:

var div1 = document.getElementById('div1');
div1.onclick = function() {
console.log(this); //当该事件被触发的时候,该this是div1
}

2. 函数中的this


只有在函数执行时刻,查看函数前面“.”是谁。如果函数前面有”.”,则“.”前面是谁则this就是谁。如果函数前面没有”.”,则此时的this就是window。 
ps:

  • (1) 函数定义的时候this是不能确定下来的,只有执行的时刻才能确定。
  • (2) 同一函数,不同的执行方式会导致函数中的this不同。

例:

function print(){
console.log(this);
}
var obj = {
fun: print
};
var ary = [print];
print(); //此时打印的this是window
obj.fun(); //此时打印的this是obj
ary[0](); //此时打印的this是ary

3. 自运行函数中的this


自运行函数中的this是window. 
例:

var obj = {
fun: (function(){
console.log(this); //自执行函数中的this是window
return function(){
console.log(this); //自执行函数自执行剩下的函数,被obj调用(obj.fn()),因此此时的this是obj
};
})()
};
obj.fn();

4. 定时器函数中的this


定时器函数中的this是window。 
例:

function fun(){
console.log(this);
}
var obj = {
fun: fun
};
setInterval(fn, 1000); //此时打印的this是window
setInterval(obj.fn, 1000); //此时打印的this是window

5. 构造函数中的this


构造函数中this是当前实例。 
例:

function Tab(){
console.log(this); //此时打印的this是Tab
}
var tab = new Tab();

6. 回调函数中的this


回调函数中的this一般也是window。 
例:

function doSomething(callback) {
console.log(this);
callback('I', 'love', 'JavaScript');
}
function foo(a, b, c){
console.log(a+' '+b+' '+c);
console.log(this);
}
doSomething(foo);

7. JS中提供的几种强制修改this方法


  • call、apply、bind均能实现轻质修改this。

上一篇: ECMAScript 2015 (ES6) 概览

下一篇: ES6新特性学习