Javascript 将成员添加到现有对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4601008/
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
Adding members to an existing object
提问by Jon Doe
Suppose we have the following object:
假设我们有以下对象:
var obj = {
fn1: function() {
}
}
how can I dynamically add another member to it, say
我怎样才能动态地向它添加另一个成员,说
fn2: function() {}
回答by Phrogz
As others have pointed out:
正如其他人指出的那样:
obj.fn2 = function(){ ... };
Note that if "fn2" is not a valid identifier, you must instead use the 'array' notation for the object:
请注意,如果“fn2”不是有效标识符,则必须对对象使用“数组”表示法:
obj["fn2"] = function(){ ... };
obj["!! crazy-names#allowed?!"] = function(){ ... };
This is also how you would do it if you had the name of the property stored in a variable:
如果您将属性的名称存储在变量中,您也会这样做:
var propName = "fn2";
obj[propName] = function(){ ... };
If you want to test if a property exists for an object, you can use the in
operator:
如果要测试对象的属性是否存在,可以使用in
运算符:
if ("fn2" in obj){ ... }
If you want to remove a property from an object, use the delete
keyword:
如果要从对象中删除属性,请使用delete
关键字:
var o = { a:42 };
console.log( "a" in o ); // true
delete o.a; // Or delete o["a"]
console.log( "a" in o ); // false
To iterate over all properties in an object, use the in
operator in a for loop. Be sure to var
the variable so that it isn't global:
要遍历对象中的所有属性,请in
在 for 循环中使用运算符。确保var
变量不是全局变量:
var o = { a:42, b:17 };
var allPropertyNames = [];
var allPropertyValues = [];
for (var propName in o){
// If you don't do this test, propName might be a property inherited
// by this object, and not a property on the object itself.
if (o.hasOwnProperty(propName)){
allPropertyNames.push(propName);
allPropertyValues.push(o[propName]);
}
}
console.log( allPropertyNames ); // [ "a", "z" ]
console.log( allPropertyValues ); // [ 42, 17 ]
回答by ChaosPandion
It's quite simple actually:
其实很简单:
obj.fn2 = function() { }
回答by eHussain
Try out following
尝试以下
var obj = {
fn1: function() {
}
}
obj.fn2 = function() {} // this will add another member to existing object
Hope this will help.
希望这会有所帮助。
Thanks!
谢谢!
Hussain.
侯赛因。
回答by Ghafoor
var obj = { };
// Adding function by extending the object using dot notation
obj.subtract = function(num1,num2){
return num1 - num2;
};
console.log(obj.subtract(8,5));//3
//Adding function by extending the object using bracket notation
obj['multiply them'] = function(num1,num2){
return num1 * num2 ;
};
console.log(obj[' multiply them '](3,3)); // 9
回答by Jimmy Chandra
you can use prototype for that...
你可以使用原型...
obj.prototype.fn2 = function() {
....
}
or just simply
或者只是简单地
obj.fn2 = function() {
....
}