Reputation: 675
I'm new to JS. If I want to assign for example 2 functions to a contructor, do I have to call a function declaration via prototype twice?
function Shape(x, y) {
this.x= x;
this.y= y;
}
Shape.prototype.foo= function() {
return ...;
};
Shape.prototype.bar= function() {
return ...;
};
Upvotes: 1
Views: 54
Reputation: 3580
If I understand you correctly, something like this will work:
function Shape(x, y) {
this.x= x;
this.y= y;
}
Shape.prototype = {
constructor: Shape,
foo: function() {
return ...;
},
bar: function() {
return ...;
}
}
Upvotes: 2
Reputation: 6562
You can do it this way, or you can assign a new object to the prototype (overwriting any existing properties / methods):
Shape.prototype = {
foo : function(){
},
bar : function(){
}
};
If you're adding lots of methods to different prototypes and you don't want to overwrite the entire prototype object, define a helper method to do the asignment for you:
function addToPrototype(constructor, obj){
for (var prop in obj){
constructor.prototype[prop] = obj[prop];
}
}
addToPrototype(Shape, {
foo : function(){
},
bar : function(){
}
});
addToPrototype(Shape, {
something : function(){
}
});
addToPrototype(Polygon, {
somethingElse : function(){
}
});
Upvotes: 1