简体   繁体   English

如何将对象中的属性分配给javascript中同一对象中某个属性的值?

[英]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.

相关问题 如何动态地将值赋给对象的相同属性? - How to dynamically assign value to same property of an object? 如何将对象属性值分配为同一对象中的键? - How to assign an object property value as a key in the same object? 如何将对象键分配给相同的属性并创建具有名称和值对的对象数组 - how to assign Object keys to a same property and create an array of objects with name and value pair-Javascript 如何检查对象属性是否存在,并有条件地分配默认值(在JavaScript中) - How to check if an object property exists, and conditionally assign default value (in JavaScript) 通过另一个对象上的字符串值为javascript对象属性分配一个值 - Assign javascript object property a value via string value on another object 如何在javascript中将对象分配给类属性 - How to assign an object to a class property in javascript 将对象属性设置为同一对象中属性的负值(Javascript / jQuery) - Set an object property to the negative value of a property in the same object (Javascript/jQuery) 如何使用变量为对象属性分配值? - How to assign a value to an object property using variable? 如何为对象属性的可变引用赋值? - How to assign a value to a mutable reference of an object property? javascript:将 object function 返回值分配给 object 属性 - javascript: assign object function return value to object property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM