[英]How to assign a property in object to the value of some property in same object in javascript?
In code below I'm creating a circle objects and giving it's keys some values.在下面的代码中,我正在创建一个圆对象并为其键指定一些值。 I'm setting the radius property of the circle object to it's diameter divided by 2. When we console.log it's value, it returns NAN.
我将圆对象的半径属性设置为它的直径除以 2。当我们 console.log 它的值时,它返回 NAN。 How to fix this problem?
如何解决这个问题?
let circle = {
posX: 40,
posY: 70,
diameter: 30,
radius: this.diameter/2
}
console.log(circle.radius)
You need a method inside the object in order to do it, because you are using the this
keyword, and it needs a function to work:您需要在对象内部有一个方法才能执行此操作,因为您使用的是
this
关键字,并且它需要一个函数才能工作:
let circle = { posX: 40, posY: 70, diameter: 30, radius: function () { return this.diameter/2; } } console.log(circle.radius())
You can use a class:您可以使用一个类:
class Circle {
posX;
posY;
diameter;
radius;
constructor(posX, posY, diameter){
this.posX = posX;
this.posY = posY;
this.diameter = diameter;
this.radius = diameter / 2;
}
}
Then when you instanciate it like the following, the radius is automatically set to diameter/2然后当你像下面这样实例化它时,半径会自动设置为diameter/2
let circle = new Circle(40, 70, 30);
// circle.radius is 15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.