Javascript add method to object
you need to add it to Foo's prototype:
function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()
add a method to Object class in javascript ES6
I would recommend to use es6 classes
class User{
constructor(user = {}){
this.name = user.name;
this.gender = user.gender;
}
isMale(){
return this.gender === 'male';
}
}
let carlos = new User({'carlos', 'male'})
carlos.isMale() // true
and if you retrieve an array of those users you could then map them in this way.usersArray = usersArray.map(user => new User(user));
How to add a method to an object's prototype
So, basically, I think this boils down to a fundamental misunderstanding of what a prototype
is. Individual instances of an object do not have a .prototype
, rather, they have an internal link to the prototype of the constructor from which the object instance was created. This was formerly known as .__proto__
(AKA dunder-proto), but has since been officially deprecated.
More recently, to reference the prototype of the constructor for an object instance, you can access a property called .constructor
. (*Note*: .constructor
may be undefined depending on how the object was created). From this, you can access the .prototype
.
Similarly, you can use Object.getPrototypeOf(obj)
and Object.setPrototypeOf(obj)
where obj
is an instance of an object.
For example:
var x = Object.create(null);console.log("x.prototype", x.prototype);
var y = Object.create({a: "foo"});console.log("y.prototype:", y.prototype);
Best Way to Add Methods to Existing Javascript Object
Yes.Is this second alternative viable and efficient?
No, the functions are reused, not re-created. All of the objects will share the single copy of theOr am I re-creating those functions and thereby creating redundant overhead?
getExt
and getTitle
functions. During the call to the functions from (say) aDocs[1]
, within the call, this
will refer to the object the function is attached to. (This only applies if you call it as part of an expression retrieving it from the object, e.g., var title = aDocs[1].getTitle();
)Alternately, if you liked, you could create new objects which shared a prototype, and copy the properties from the aDocs
objects to the new objects, but you've asked about assigning new functions to existing objects, so...
Javascript: Add method to all objects in array
Well, those objects don't have a special prototype, so you can't add members to it. I think these are the alternatives:
1) Add the members to each instance (I know you don't like it, but it's an option). I'd go for this option
2) Just create a method, and pass each object as a parameter or as this
with fn.call()
3) Create a "class" with the added members, then create instances of it passing the original object in the constructor. Not ideal, but maybe you have to do it.
function Color(plainObj){
this.colorName: plainObj.colorName;
this.colorIsInRainbow: plainObj.colorIsInRainbow;
//if you want all properties to be copied dynamically, uncomment the following:
//for(var key in plainObj) this[key] = plainObj[key];
this.userClickedThisColor = ko.observable()
...
}
Color.prototype.colorStartsWithR = function() {
return this.colorName.charAt(0) == "R";
};
//etc
Then, to apply itfor(var i=0; i<colorData.length; i++){
colorData[i] = new Color(colorData[i]); //Overwrites original colorData array
}
Hope this helps. Cheers How to add methods dynamically to a javascript object
You can't use new
without a constructor. For your object literal you do not even need a class/constructor. Just attach a new property.
sampleFunction(() => console.log("This is new function"))
function sampleFunction(newMethod) {
var Person = {
first_name: "Marty",
last_name: "Mcfly",
born: 1968,
};
Person.newMethod = newMethod;
console.log(Person);
Person.newMethod();
}
Adding elements to object
Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} }
then perform:var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
JSON.stringify()
was mentioned as a concern in the comment:>> JSON.stringify([{a: 1}, {a: 2}])
"[{"a":1},{"a":2}]"
Related Topics
Removing Duplicate Objects with Underscore for JavaScript
How to Stop Intense JavaScript Loop from Freezing the Browser
Create Copy of Multi-Dimensional Array, Not Reference - JavaScript
Finding "Line-Breaks" in Textarea That Is Word-Wrapping Arabic Text
Passing a PHP Variable to JavaScript in a Blade Template
Getusermedia() in Chrome 47 Without Using Https
How to Show Current Time in JavaScript in the Format Hh:Mm:Ss
How to Subscribe to Topics with Web Browser Using Firebase Cloud Messaging
How to Replace Last Occurrence of Characters in a String Using JavaScript
How to Achieve Dynamic Scoping in JavaScript Without Resorting to Eval
JavaScript Request Fullscreen Is Unreliable
Adding Custom Http Headers Using JavaScript
How to Sum the Values of a JavaScript Object
Can Jquery Read/Write Cookies to a Browser