的功能顯得相當精緻。您執行的console.log是舊值,並且不訪問該對象上的屬性。將sideLength
設置爲10後,您不會爲該sideLength
請求新的calcPerimeter
。而你需要訪問sideLength
的square
對象像square.sideLength
// to change sideLength
this.set_sideLength = function(new_sideLength) {
this.sideLength = new_sideLength;
};
var square = new Object();
square.sideLength = 6;
square.set_sideLength = set_sideLength;
// Calculate perimeter
square.calcPerimeter = function() {
return this.sideLength * 4;
};
var p = square.calcPerimeter();
// output
console.log("Perimeter is: " + p + ", if side length is "+ square.sideLength);
// New ouptput with new sideLength
square.set_sideLength(10);
p = square.calcPerimeter();
console.log("Perimeter is: " + p + ", if side length is "+ square.sideLength);
像@Felix克林提到你或許應該改變
// from
this.set_sideLength = function(new_sideLength) {
this.sideLength = new_sideLength;
};
// to
function set_sideLength(new_sideLength) {
this.sideLength = new_sideLength;
};
分配開玩笑根據this
的實際情況,可能會對this
上的房產產生不同的影響。在你的上下文中可能代表window
對象。這就是爲什麼以下工作。
```
square.set_sideLength = set_sideLength;
```
一般來說它被認爲是不好的做法,將屬性添加到window對象。因此,你會更好地使用其他方法,並且整個事情都是IIFE。
像這樣
(function() {
'use strict';
// to change sideLength
function set_sideLength(new_sideLength) {
this.sideLength = new_sideLength;
}
var square = new Object();
square.sideLength = 6;
square.set_sideLength = set_sideLength;
// Calculate perimeter
square.calcPerimeter = function calcPerimeter() {
return this.sideLength * 4;
};
var p = square.calcPerimeter();
// output
console.log("Perimeter is: " + p + ", if side length is "+ square.sideLength);
// New ouptput with new sideLength
square.set_sideLength(10);
p = square.calcPerimeter();
console.log("Perimeter is: " + p + ", if side length is "+ square.sideLength);
})();
如果你看一下控制檯你就會知道爲什麼它不工作:'回覆ferenceError:sideLength未定義。 –
是的。 sideLength = 6然後我試圖改爲10. –
'square.sideLength = 6;'設置**對象**'square'的**屬性**'slideLength'。它沒有**創建**變量**'sideLength'。你真的認爲瀏覽器更可能出現錯誤,而不是你?如果控制檯顯示某個未定義的錯誤,那麼它沒有被定義。 –