Js中this关键字的指向

1.媒介

在主流的面向对象的语言中(比方Java,C#等),this 寄义是明白且详细的,即指向当前对象,平常在编译期绑定。而 JavaScript 中this 在运行期举行绑定的,这是JavaScript 中this 关键字具有多重寄义的实质缘由。
JavaScript 中的 this 可所以全局对象、当前对象或许恣意对象,这完整取决于函数的挪用体式格局。

2.JavaScript this决策树

《Js中this关键字的指向》

3.实例申明

  • 例1.

var point = { 
    x : 0, 
    y : 0, 
    moveTo : function(x, y) { 
        this.x = this.x + x; 
        this.y = this.y + y; 
    } 
};
point.moveTo(1,1); //this 绑定到当前对象,即point对象

图解point.moveTo函数的this指向什么的剖析图如下图所示:
《Js中this关键字的指向》

  • 例2:

function func(x) { 
    this.x = x; 
} 
func(5); //this是全局对象window,x为全局变量
x;//x => 5

图解func函数的this指向什么的剖析图如下图所示:
《Js中this关键字的指向》

  • 例3:

var point = { 
    x : 0, 
    y : 0, 
    moveTo : function(x, y) { 
    // 内部函数
        var moveX = function(x) { 
            this.x = x;//this 指向什么?window
        }; 
    // 内部函数
        var moveY = function(y) { 
            this.y = y;//this 指向什么?window
        }; 
    moveX(x); 
    moveY(y); 
    } 
}; 
point.moveTo(1,1); 
point.x; //=>0 
point.y; //=>0 
x; //=>1 
y; //=>1

申明:
point.moveTo(1,1)函数现实内部挪用的是moveX()和moveY()函数, moveX()函数内部的this在 “JavaScript this决策树“中举行剖断的历程是如许的:
1)moveX(1)函数挪用是用new举行挪用的么?这个显著不是,进入“否”分支,即函数是不是用dot(.)举行挪用?;
2)moveX(1)函数不是用dot(.)举行挪用的,即进入“否”分支,即这里的this指向全局变量window,那末this.x现实上就是window.x;

  • 例4.作为组织函数挪用的例子:

function Point(x,y){ 
    this.x = x; // this ?
    this.y = y; // this ?
}
var np=new Point(1,1);
np.x;//1
var p=Point(2,2);
p.x;//error, p是一个空对象undefined
window.x;//2

申明:
Point(1,1)函数在var np=new Point(1,1)中的this在 “JavaScript this决策树“中举行剖断的历程是如许的:
1)var np=new Point(1,1)挪用是用new举行挪用的么?这个显著是,进入“是”分支,即this指向np;
2)那末this.x=1,即np.x=1;
Point(2,2)函数在var p= Point(2,2)中的this在 “JavaScript this决策树“中举行剖断的历程是如许的:
1)var p= Point(2,2)挪用是用new举行挪用的么?这个显著不是,进入“否”分支,即函数是不是用dot(.)举行挪用?;
2)Point(2,2)函数不是用dot(.)举行挪用的?剖断为否,即进入“否”分支,即这里的this指向全局变量window,那末this.x现实上就是window.x;
3)this.x=2即window.x=2.

  • 例5.用call 和apply举行挪用的例子:

function Point(x, y){ 
    this.x = x; 
    this.y = y; 
    this.moveTo = function(x, y){ 
        this.x = x; 
        this.y = y; 
    }; 
} 
var p1 = new Point(0, 0); 
var p2 = {x: 0, y: 0}; 
p1.moveTo.apply(p2, [10, 10]);//apply现实上为p2.moveTo(10,10)
p2.x//10

申明:
apply 和 call 这两个要领许可切换函数实行的上下文环境(context),即 this 绑定的对象。
p1.moveTo.apply(p2,[10,10])现实上是p2.moveTo(10,10)。那末p2.moveTo(10,10)可解释为:
1)p2.moveTo(10,10)函数挪用是用new举行挪用的么?这个显著不是,进入“否”分支,即函数是不是用dot(.)举行挪用?;
2)p2.moveTo(10,10)函数是用dot(.)举行挪用的,即进入“是”分支,即这里的this指向p2.moveTo(10,10)中.之前的对象p2,所以p2.x=10;

    原文作者:Evan_Chen
    原文地址: https://segmentfault.com/a/1190000004641776
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞