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);
If you want to insert an element at a given position, use the insert(pos, obj) method. It accepts one object and adds that object at the position pos of the list on which it is called.
Use this:
myFunction.bookName = 'mybook'; myFunction.bookdesc = 'new';
Or, if you are using jQuery:
$(myFunction).extend({ bookName:'mybook', bookdesc: 'new' });
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With