我可以在 javascript 中动态添加属性吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4326834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I add a property dynamically in javascript?
提问by capdragon
Is it okay to add properties to an object at runtime? It seems to run okay but are there any issues I should be aware of?
可以在运行时向对象添加属性吗?它似乎运行正常,但有什么我应该注意的问题吗?
I'm using a 3rd party javascript API which has an object class, which I've instantiated and added my own property to after instantiation, like the code below:
我正在使用 3rd 方 javascript API,它有一个对象类,我已经实例化并在实例化后添加了我自己的属性,如下面的代码:
For example can I do this:
例如,我可以这样做:
var Car = function (id, type) {
this.id = id;
this.type = type;
};
var myCar = new Car(1,"Nissan");
// CAN I DO THIS: (needsWork not a property of object Car)
myCar.needsWork = true;
回答by ?ime Vidas
Yea, this is called object augmentation. It is a key feature in JavaScript.
是的,这称为对象增强。它是 JavaScript 中的一个关键特性。
回答by Sean Patrick Floyd
Actually, you have two ways to do that in JavaScript:
实际上,在 JavaScript 中有两种方法可以做到这一点:
add a method or property to an instance (this car only)
var myCar = new Car(1,"Nissan"); myCar.needsWork = true;add a method or property to the car prototype (all cars, even already existing ones)
var myCar = new Car(1, "Nissan"); var biggerCar = new Car(2, "Hummer"); Car.prototype.needsWork = true; alert( myCar.needsWork && biggerCar.needsWork ? "We need work" : "Something wrong here" );
向实例添加方法或属性(仅限本车)
var myCar = new Car(1,"Nissan"); myCar.needsWork = true;向汽车原型添加方法或属性(所有汽车,甚至已经存在的汽车)
var myCar = new Car(1, "Nissan"); var biggerCar = new Car(2, "Hummer"); Car.prototype.needsWork = true; alert( myCar.needsWork && biggerCar.needsWork ? "We need work" : "Something wrong here" );
Reference:
参考:
回答by Adam
Yes
是的
There is nothing wrong with that.
没有什么不妥。
See Object Augmentation here: http://www.crockford.com/javascript/inheritance.html
请参阅此处的对象增强:http: //www.crockford.com/javascript/inheritance.html

