由对象数组引申||this的探讨

来源:互联网 发布:讲文明知礼仪内容15个 编辑:程序博客网 时间:2024/04/30 13:32

在学习对象数组的时候,对这对象内保存数据的方法比较感兴趣,于是执行了一遍书上给的代码。

  function weekTemps(){        this.dataStore=[];        this.add=add;        this.average=average;    }    function add(temp){        this.dataStore.push(temp);        }    function average(){        var total=0;        for(var i=0;i<this.dataStore.length;i++){            total+=this.dataStore[i];        }        return total/this.dataStore.length;    }    var thisWeek=new weekTemps();    thisWeek.add(45);    thisWeek.add(56);    thisWeek.add(34);    thisWeek.add(76);    thisWeek.add(23);    console.log(thisWeek.average());

发现报有“cannot read property ‘push’ of undefined” 的错误。
‘push’方法没有加成功,再试了一下’map’也报错,不是方法的原因那么就得考虑是对象的原因了。—–“this.dataStore”没有取到dataStore对象。
为什么’this.dataStore’会出问题呢?

这里我们就要对this做一下探讨了。this,是JavaScript中的一个关键字,经常在函数中看到它。判断this的指向,就得看this所在的函数属于谁。 这个语句是写在add函数里的,而add又是全局函数,是全局性的调用,所以this指向了window。也就是说add函数里面实则是’window.dataStore.push(temp)’, push方法无法给Window对象添加数值,所以控制台就报错。那为什么weekTemps函数里的this没有报错呢?因为weekTemps是一个构造函数,构造函数中的this指向新创建的对象。

弄明白哪里出错了后,再来修改代码。

1.把add函数放入引用add函数的位置,这样就可以让this指向调用add函数的方法。

  function weekTemps(){        this.dataStore=[];        this.add=add;        this.average=average;       function add(temp){        this.dataStore.push(temp);        }    }

不能够将函数提取出来再在weekTemps来调用。

   function weekTemps(){                this.dataStore=[];                this.add=add;                this.average=average;                add(temp);            }             function add(temp){                this.dataStore.push(temp);    }       

2.使用函数表达式。

 var add=function(temp){            this.dataStore.push(temp);    }

关于this的总结:

1.当函数作为对象的方法调用时,this指向该对象。/ 函数有所属对象时:指向所属对象/函数没有所属对象:指向全局对象

2.当函数作为淡出函数调用时,this指向全局对象(严格模式时,为undefined)

3.构造函数中的this指向新创建的对象/ 构造器中的 this:指向新对象

4.嵌套函数中的this不会继承上层函数的this,如果需要,可以用一个变量保存上层函数的this。

5.apply 和 call 调用以及 bind 绑定:指向绑定的对象

如果在函数中使用了this,只有在该函数直接被某对象调用时,该this才指向该对象。

1)obj.foocoder();
2)foocoder.call(obj, …);
3)foocoder.apply(obj, …);

0 0
原创粉丝点击