你能解釋一下爲什麼這個對象不理解'this'嗎?在創建javascript對象時使用(使用這個)
var circle = {
radius : 20,
x : 100 - this.radius/2,
y : 100 - this.radius/2,
}
console.log(circle.x) // returns NaN, why?
你能解釋一下爲什麼這個對象不理解'this'嗎?在創建javascript對象時使用(使用這個)
var circle = {
radius : 20,
x : 100 - this.radius/2,
y : 100 - this.radius/2,
}
console.log(circle.x) // returns NaN, why?
因爲這不是如何this
作品JS。 this
只會在您以某種方式引用您的對象導致您的對象被指定爲this
函數調用上下文的值。
在創建對象時,您不能引用對象字面值,因爲它尚不存在。
如果你正在創建圈子,你可以考慮使用一個構造函數:
function Circle(radius) {
this.radius = radius,
this.x = 100 - this.radius/2,
this.y = 100 - this.radius/2,
}
var circle_20 = new Circle(20);
因爲你使用new
,this
構造函數調用內調用Circle
作爲構造將是一個參考正在創建的對象。由於您沒有顯式地返回其他對象,因此該對象被隱式返回。
由於正被定義,其中,this
不是circle
對象。
如何:
var circle = {
radius: 20,
getX: function() { return (100) - this.radius/2; },
getY: function() { return (100) - this.radius/2; }
}
您獲得的結果,因爲,在這種情況下,這並不是指被創建的對象。
在JavaScript中沒有辦法做你正在嘗試的東西(在對象聲明中)。唯一的解決方法是這樣的:
var newRadius = 20
var circle = {
radius: newRadius,
x: 100 - newRadius/2,
y: 100 - newRadius/2
};
console.log(circle.x);
該對象尚不存在。它在之後只存在,所以在計算它使用該對象時爲時尚早。
相反,你可以在一個封閉計算值,讓您可以放心地單獨計算它們,並返回對象:
var circle = (function() {
var radius = 20,
x = 100 - radius/2,
y = 100 - radius/2;
return { radius: radius,
x: x,
y: y };
})();
// now circle is the wanted object,
// and you don't leave the `var` variables separately.
下面是一個簡單的例子:
//Saul was born: Initialize the parent!
var parent = {
youngestChild: 'Small Saul'
};
//Tim was born: Overwrite the parent!
parent = {
youngestChild: 'Tiny Tim',
currentYoungestChild: parent.youngestChild
};
alert(parent.currentYoungestChild);
誰是parent.currentYoungestChild
?
與許多開發者一樣,我認爲parent.youngestChild
將被設置爲'Tiny Tim'
,然後它將被設置爲parent.child
。如果是這種情況,它將被設置爲'Tiny Tim'
。
然而,事實證明,所有的孩子都被存儲在他們的父母之前評估,所以
parent.currentYoungestChild == 'Small Saul'
Here的小提琴,如果你想嘗試一下。
對此功能的一種解釋是因爲子聲明的順序無關緊要。例如,下面將有一個不同的結果,如果對象進行了評估,並存儲順序:
parent = {
currentYoungestChild: parent.youngestChild,
youngestChild: 'Tiny Tim'
};
長話短說:在對象的聲明與其他子元素初始化子元素都不行!