2014-02-23 36 views
0

我在这里有一小段代码,这是我坚持使用的一些情况的模型。对于我来说,作为一名PHP程序员,这在PHP中很容易实现,但我从不知道如何在JS中做到这一点。也许有人可以帮忙。 (怪的jQuery为)如何调用对象的方法和使用变量

var counterObj = { 

items: [1,4,7], 

total: 0, 

run: function() { 

    $.each(this.items, function(i, item){ 
     // Call my own method 
     this.add(item); 
    }) 
    .promise() 
    .done(function(){ 

     // doubt it will log 12 
     console.log(this.total); 
    }); 
}, 

add: function(item){ 
    this.total = this.total + item; 
} 
}; 

counterObj.run(); 

http://jsfiddle.net/EH9qK/

+2

promose .........我会阅读文档再次 –

+0

'.promose()'是一个新的方法或东西 –

+0

不,我固定的, 拼写错误。希望你只是想搞笑。 –

回答

1
run: function() { 
    $.each(this.items, function(i, item){ 
     this.add(item); 
    }) 
    .promise() 
    .done(function(){ 
     console.log(this.total); 
    }); 
} 

this$.each指的是你的阵列中的数相反,你应该这样做:

run: function() { 
    var _this = this; 
    $.each(this.items, function(){ 
     _this.add(this); //so many "this" 
    }); 
    console.log(this.total); 
} 

http://jsfiddle.net/DerekL/EH9qK/4/

顺便说一句,jQuery对象中只存在和.done$.each返回原始数组。


在JavaScript thisa really confusing keyword。它也可以与.apply,这是jQuery的在它的方法做了改变:

值也可以通过this关键字访问,但是JavaScript的始终包裹this值,即使它是一个对象一个简单的字符串或数字值。
jQuery's docs

但即使jQuery是不修改this,它仍然会指错了对象(window)。

Oh yea,1 + 4 + 7 is 12,not 13。 :)

+0

我不建议使用变量的“自我”,因为它在browsers.'that指向“窗口”对象默认”或‘_this’会更具有可读性。 –

+0

@UdiCohen - 谢谢,改变了。 –

0

您声明的每个函数都会创建另一个作用域。你所要做的就是通过调用bind'方法'将函数绑定到counterObject。我不明白'承诺'的使用,但我试图尽可能少地改变代码,所以我的更改将变得清晰。

var counterObj = { 

    items: [1,4,7], 

    total: 0, 

    run: function() { 

     $.each(this.items, function(i, item){ 
      // Call my own method 
      this.add(item); 
     }.bind(this)) 
     .promise() 
     .done(function(){ 

      // doubt it will log 13 
      console.log(this.total); 
     }.bind(this)); 
    }, 

    add: function(item){ 
     this.total = this.total + item; 
    } 
}; 

counterObj.run(); 
0

您需要返回应该从您的范围公开的功能,否则它们被认为是私有的。

对于示例:

var counterObject = { 
    ... 
    return { 
     run: run 
    }; 
};