将新元素添加到现有对象 [英] Add new element to an existing object

查看:69
本文介绍了将新元素添加到现有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方法来向现有对象添加新元素,例如数组推送的内容

I was looking for a way to add new elements to an an existing object like what push does with arrays

我试过这个并且它不起作用:

I have tried this and it didn't work :

var myFunction = {
    Author: 'my name ',
    date: '15-12-2012',
    doSomething: function(){
        alert("helloworld")
    }
};
myFunction.push({
    bookName:'mybook',
    bookdesc: 'new'
});
console.log(myFunction);


推荐答案

使用此:

myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';

或者,如果您使用的是jQuery:

Or, if you are using jQuery:

$(myFunction).extend({
    bookName:'mybook',
    bookdesc: 'new'
});

推送方法错误,因为它属于到 Array.prototype 对象。

The push method is wrong because it belongs to the Array.prototype object.

要创建命名对象,请尝试以下操作:

To create a named object, try this:

var myObj = function(){
    this.property = 'foo';
    this.bar = function(){
    }
}
myObj.prototype.objProp = true;
var newObj = new myObj();

这篇关于将新元素添加到现有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆