在创建时引用javascript对象属性(使用此属性)
你能解释一下为什么这个物体不理解“这个”吗在创建时引用javascript对象属性(使用此属性),javascript,oop,Javascript,Oop,你能解释一下为什么这个物体不理解“这个”吗 var circle = { radius : 20, x : 100 - this.radius / 2, y : 100 - this.radius / 2, } console.log(circle.x) // returns NaN, why? 因为在定义的地方,此不是圆对象 那么: var circle = { r
var circle = {
radius : 20,
x : 100 - this.radius / 2,
y : 100 - this.radius / 2,
}
console.log(circle.x) // returns NaN, why?
因为在定义的地方,
此
不是圆
对象
那么:
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);
工作方式<代码>此
仅当您以某种方式将对象指定为函数调用上下文的此
值时,才会作为对对象的引用如果你正在创建圆圈,你可以考虑使用构造函数:
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
作为构造函数调用Circle
,构造函数调用中的将引用正在创建的对象。该对象隐式返回,因为您没有显式返回其他对象。该对象尚不存在。它只在计算完所有东西后才存在,所以在计算时使用对象还为时过早
相反,您可以计算闭包中的值,这样您就可以安全地分别计算它们,并返回对象:
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.youngestChild
在设置为parent.child
之前应该先设置为'Tiny Tim'
。如果是这种情况,它将被设置为“Tiny Tim”
然而,事实证明,所有子项在存储到其父项上之前都会进行评估,因此
parent.currentYoungestChild == 'Small Saul'
如果你想试一试的话,那是一把小提琴
对此功能的一种解释是,子声明的顺序并不重要。例如,如果按顺序计算和存储对象,则以下结果会有所不同:
parent = {
currentYoungestChild: parent.youngestChild,
youngestChild: 'Tiny Tim'
};
长话短说:从对象声明中的其他子元素初始化子元素将不起作用强>