[英]javascript class instance object literal
Is there a shorthand way to add properties to an instance of a class in javascript?是否有一种速记方法可以在 javascript 中向类的实例添加属性?
Edit: The duplicate answers are about adding properties to an object not a class.编辑:重复的答案是关于向对象而不是类添加属性。 I'm trying to make it easy for the user to add about 10-20 properties.
我试图让用户轻松添加大约 10-20 个属性。 I'm also trying to make sure they can't add their own properties but can only add values to the predefined properties.
我还试图确保他们不能添加自己的属性,而只能向预定义的属性添加值。 I don't know how to do that.
我不知道该怎么做。
I have a javascript "class":我有一个 javascript“类”:
function Car(){
this.make="";
this.model="";
//...
}
To create an instance and add properties I would use:要创建一个实例并添加属性,我会使用:
var mycar = new Car();
mycar.make="honda";
mycar.model="civic";
//...
Is there a shorthand way to create an instance and add the properties so I don't have to type "mycar."是否有一种快捷方式来创建实例并添加属性,这样我就不必键入“mycar”。 each time?
每一次?
If your constructor doesn't do anything important, you can use Object.create()
:如果你的构造函数没有做任何重要的事情,你可以使用
Object.create()
:
function Car() { //... } console.log( Object.create( Car.prototype, Object.getOwnPropertyDescriptors( { make: 'honda', model: 'civic' } ) ) );
I wouldn't exactly call this "shorthand", but it is a single statement, and it omits invoking Car()
if your constructor's body is redundant.我不会完全称之为“速记”,但它是一个单一的语句,如果您的构造函数的主体是多余的,它会省略调用
Car()
。
I'd personally recommend using Object.assign()
within the body of your constructor
:我个人建议在
constructor
的主体中使用Object.assign()
:
function Car(props) { /* to formally mimic behavior of default parameters specification */ // props = arguments.length < 1 || props === undefined ? {} : props; /* commonly used "good-enough" ES5 equivalent */ props = props || {}; Object.assign(this, props); } console.log( new Car({ make: 'honda', model: 'civic' }) );
Or ES6:或 ES6:
class Car { constructor (props = {}) { Object.assign(this, props); } } console.log( new Car({ make: 'honda', model: 'civic' }) );
You should use the constructor's parameters:您应该使用构造函数的参数:
function Car(make, model) {
this.make = make;
this.model = model;
}
var mycar = new Car("honda", "civic");
You can use Object.assign
function.您可以使用
Object.assign
函数。
function Car() { this.make = ""; this.model = ""; } var mycar = new Car(); Object.assign(mycar, { make: "honda", model: "civic" }); console.log(mycar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.