I don't like the following since it repeats Child.prototype
many times:
function Parent(a)
{
this.a = a;
}
function Child(a, b)
{
Parent.call(this, a);
this.b = b;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.childValue = 456;
Child.prototype.anotherChildValue = 457;
Child.prototype.yetAnotherValue = 458;
Child.prototype.IHateToWriteChildPrototypeEachTime = 459;
// ...gazillion more Child.prototype.xxx
I would like the following way of specifying new members instead:
{
constructor: Child,
childValue: 456,
anotherChildValue: 457,
yetAnotherValue: 458,
ILoveThisSinceItsSoTerse: 459,
// ...gazillion more
}
Is there a nice, clean and efficient way of doing this, without creating helper functions and reinventing the wheel in general?
You can make a very simple extend
function to do what you wish:
var extend = function(obj, methods) {
for(var key in methods) {
if(methods.hasOwnProperty(key)) {
obj[key] = methods[key];
}
}
}
And then you can say:
extend(Child.prototype, {
constructor: Child,
foo: function() { }
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.