search

Home  >  Q&A  >  body text

javascript闭包 - Javascript中this的指向问题

我是小白,今天写了一个小函数

Array.prototype.a = function(){
    var k = 0;

for(x in this)
{

    k+=this[x];
}
console.log(k);
}
var t = [1,2,3,7]
t.a()

结果打印出来是

13function (){
var k = 0;
for(x in this){
k+=this[x];
}
console.log(k);
}

请问为什么this会指向函数本身呢?

追问:我为了知道this的内容,还专门打印this的内容,显示为【1,2,3,7】

天蓬老师天蓬老师2895 days ago270

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-10 15:22:29

    这里的this应该是Array的对象,也就是 t。

    由于你使用 for in 循环遍历对象的属性,所以原型链上的所有属性都将被访问。也即你定义 function a 会被遍历。

    所以this[a]返回结果就是function,由于在操作符 + ,会自动tostring, 也就是你看到输出结果。

    另外对于array,最好不要使用 for in 循环遍历。

    下面代码应该是你想要的结果:

    Array.prototype.a = function (){
        var k = 0;
    
        for (var i =0, c; c = this[i++];) {
            k += c;
        }
    
        console.log(k);
    }
    var t = [1,2,3,7]
    t.a()
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 15:22:29

    你首先在原型链上增加了一个a属性方法,this指向的是t,for..in 循环的时候,将数组里的数值都加起来,然后加上了a方法,所以最后是你看到的这个样子

    reply
    0
  • 迷茫

    迷茫2017-04-10 15:22:29

    for in 循环会遍历对象的属性
    对象中的_proto_对象也将会被遍历出来
    t 数组就是 new 了Array();
    t._proto_===Array.prototype
    所以也会把a函数给遍历出来,一楼的解释是对的

    reply
    0
  • Cancelreply