前端this的指向问题

一般来说:

1. 普通函数:this 指向调用其所在函数的对象(对于继承等是就近原则,离谁近指向谁),

                     即常说的运行时绑定。

2.call & apply & bind: 可以改变this指向,但是通过bind方法绑定后,

                                     函数将被永远绑定在其第一个参数对象上

3.window全局方法:this指向window对象(本质上就是普通函数,不过调用者是window)

4.构造函数:this是被创建的新对象

5.DOM事件:this指向触发事件的元素

6.箭头函数(=>):没有自己的this, 它会将其所在(定义的位置)上下文的this值, 作为自己的this值,                                  即常说的定义时绑定this。

全局环境下:

this 始终指向全局对象(window), 无论是否严格模式;

console.log(this === window); // true
this.a = 11;
console.log(window.a); // 11

普通函数:

this 指向调用其所在函数的对象

function f1(){
  return this;
}
function f2(){
  "use strict"; // 这里是严格模式
  return this;
}
var ss = {
  f1:function(){
    return this;
  },
  f2:function(){
    "use strict"; // 这里是严格模式
    return this;
  },
}

f1() === window; // true
f2() === undefined; // true
ss.f1() === ss; // true
ss.f2() === ss; // true

call & apply:

可以改变this指向

function f1(){
  return this.a;
}
var o = {a:33};
f1.call(o); //33
f1.apply(o); //33

window全局方法

例如:alert、confirm、prompt、setTimeout、setInterval、onload、onresize等this指向window对象

var tt = {
    a:'111',
    ff:function(){
        setTimeout(function() {
            console.log(this);
        }, 0);
    }
}
tt.ff(); //Window

构造函数:

this是被创建的新对象

function f1(){
  this.a = 22;
}
var o = new f1();
o.a === 22 //true

DOM事件:

(1)当代码被包括在函数内部执行时,类似普通函数,this指向其调用者;

(2)直接处理时,this指向所在的DOM元素

<button onclick="console.log(this)">11111111111</button> 
//结果:<button onclick="console.log(this)">11111111111</button>
<button onclick="(function(){console.log(this)})()">22222222222</button> //结果:Window
<button onclick="(function(){'use strict';console.log(this)})()">33333333333</button> //undefined

箭头函数:

待续。。。

 

猜你喜欢

转载自my.oschina.net/u/3019884/blog/1808772