我正在阅读 crockford 的 Javascript: The Good Parts 并且正在研究调用模式类(class)中的这段代码:
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
调用 double
方法后,我得到了 undefined
。有谁知道为什么吗?
最佳答案
您的“add()”函数缺少一个return
语句:
var add = function(a,b) {
return a + b;
}
实际上没有return
语句的函数"returns" undefined .
关于javascript - 对 `this` 关键字的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6934333/