看了這篇我也懂了this

// this指向
// 1.指向全局變量window
var a = 1;

function func() {
    var a = 2;
    console.log(this.a);
}
func(); //2
// 2.指向調(diào)用它的對象(funx()中的this只對直屬上司(直接調(diào)用者obj)負(fù)責(zé),不管有多少個。)
var b = 3;

function funx() {
    console.log(this.b);
}
var obj = {
    b: 4,
    funx
}
obj.funx(); //4

var aa = 15

function test() {
    console.log(this.aa)
}
var obj = {
    aa: 2,
    test
}
var obj0 = {
    aa: 3,
    obj
}
obj0.obj.test()
// 3.可以將其傳給一個變量,并且一樣調(diào)用它
var d = 1

function test() {
    console.log(this.d)
}
var obj = {
    d: 2,
    test
}
var testCopy = obj.test
testCopy();
// 4.call(),命令指向誰
var e = 7;

function test1() {
    console.log(this.e)
}
var obj = {
    e: 8,
    test1
}
var testCopy = obj.test1
testCopy.call(obj);
// 5.指向構(gòu)造函數(shù)實例化對象
var e = 9;

function Fu(e) {
    this.e = e
}
var rr = new Fu(10);
console.log(rr.e);
// 6.箭頭函數(shù)中的this在函數(shù)定義的時候就已經(jīng)確定,它this指向的是它的外層作用域this的指向。
var u = 11;
var test = () => {
    console.log(this.u);
}
var obj = {
    u: 18,
    test
}
obj.test();


作者:Vam的金豆之路

主要領(lǐng)域:前端開發(fā)

我的微信:maomin9761

微信公眾號:前端歷劫之路