首页 > Web开发 > 详细

js中 this 的指向

时间:2019-07-04 17:00:34      阅读:146      评论:0      收藏:0      [点我收藏+]

js中 this的指向一共存在3种地方:

1.全局的this;

2.构造函数的this;

3.call/apply;

一、全局的this:

 1 function test(){
 2     this.d = 3;//函数的默认指向是window
 3     var a = 1;
 4     function c(){
 5     }
 6 }
 7 
 8 test(123);
 9 console.log(window.d);
10 console.log(this.d);//this 默认指向window

这里有两个点:函数的默认指向是window;全局this 指向 window;

预编译的过程:

 ao:
     this : window
     a
     c :function c(){}
    
    go:
        test :function test(){}

这里的两个console.log输出的都是3

二、构造函数中this的指向:

1     function Test(){
2         this.name = "123";
3         }
4     var test = new Test();

这里的预编译过程是这样的:

GO:Test :function Test(){};

AO:

第一次:this {window};

当new了之后: this : {name:123; __proto__:Test.prototype}

三、call/apply改变this的指向

 1 //call/apply 改变this指向
 2 function Person(){
 3         this.name = "张三";
 4         this.age = 18
 5     }
 6 function Programmer(){
 7     Person.apply(this);
 8     this.work = "Progarmming";
 9 }    
10 
11 var p = new Programmer();
12 console.log(p);

根据前面的介绍,可知:Person.apply(this);中this 是指向Programmer的实例化对象,  此处 的this也替换了Person 实例化对象;所以 最后输出就是:
{name: "张三", age: 18, work: "Progarmming"}

 

总结:

1.全局this 指向 window

2.预编译函数 this指向window

3.构造函数的this 指向实例化对象

4.apply/call改变this的指向

 

 

 

 


 

js中 this 的指向

原文:https://www.cnblogs.com/lixiuming521125/p/11133265.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!