码迷,mamicode.com
首页 > 其他好文 > 详细

this的指向问题

时间:2020-02-15 21:43:10      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:settime   function   span   ret   int   timer   this   code   构造   

1.this在构造函数中,在对象的方法中,this指向当前对象

对象的方法中
        var person={
            ‘name‘:‘xm‘,
            ‘setSex‘:function(){
                this.sex=sex; 
                console.log(this); //person这个函数
            }
        }
        console.log(person.setSex);
构造函数中(构造函数创建对象)
        function parent(name,age,sex){
            this.name=name;
            this.age=age;
            this.show=function(){
               return this.sex=sex;
            }
            console.log(this); //this指向parent
        }
        var p1=new parent(‘xh‘,12,‘male‘); 
        p1.show();
        console.log(p1.sex); //male
构造函数的this指向new返回的对象

 2.在call和apply参数中,this的指向是第一个参数

cal和apply方法可以冒充对象,并使用该对象的方法 

var x=0; function test(){ alert(this.x); //0 console.log(this); //window } var p={}; p.x=1; p.show=test; p.show.apply(); //this没有指定,故指向windowvar x=0; function test(){ alert(this.x); //1 console.log(this); //p } var p={}; p.x=1; p.show=test; p.show.apply(); p.show.apply(p); //this指向p对象
总结:this只有在函数被调用时才能确定下来,this指向调用函数的对象

 3.DOM元素的监听处理函数的this指向监听器所在的DOM对象

window.setTimeout()和window.setInterval()的函数中的this默认时window对象

var name=‘Lita‘;
 var timer=setTimeout(function(){
     var name=‘L‘;
     console.log(this.name); // 打印Lita
 },1000);

 

 

this的指向问题

标签:settime   function   span   ret   int   timer   this   code   构造   

原文地址:https://www.cnblogs.com/lita07/p/12309132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!