我读克罗克福德的JavaScript:好的部分,并正在与这段代码从教训调用模式乱搞:该double
方法被称为混淆`this`关键字
var br = "<br />";
var add = function(a,b) {
a + b;
}
var myObject = {
value: 0,
increment: function(inc) {
this.value += typeof inc === "number" ? inc : 1;
}
};
myObject.increment(2);
document.write(myObject.value + br); // 2
myObject.increment();
document.write(myObject.value + br); // 3
myObject.increment(3);
document.write(myObject.value + br); // 5
myObject.double = function() {
var that = this;
var helper = function() {
that.value = add(that.value,that.value);
return that.value;
};
helper();
};
myObject.double();
document.write(myObject.value); //undefined
后,我得到undefined
。有谁知道为什么?
我不认为这是问题的根源,但使用保留字作为,不建议在JavaScript标识符。 'double'是一个保留字。 – Jacob
@Jacob:50%正确:允许Javascript中特定数据类型的计划不再存在,因此double不再位于最新标准中的保留字列表中。由于许多人仍然使用早期的浏览器,这被定义为保留字,所以应该避免使用它。 – Pindatjuh