I have this JavaScript:
var Type = function(name) {
this.name = name;
};
var t = new Type();
Now I want to add this:
v
update: An updated version here
what you were actually looking for was extending Type into another Class. There are a lot of ways to do that in JavaScript. I'm not really a fan of the new
and the prototype
methods of building "classes" (I prefer the parasitic inheritance style better), but here's what I got:
//your original class
var Type = function(name) {
this.name = name;
};
//our extend function
var extend = function(cls) {
//which returns a constructor
function foo() {
//that calls the parent constructor with itself as scope
cls.apply(this, arguments)
//the additional field
this.extraField = 1;
}
//make the prototype an instance of the old class
foo.prototype = Object.create(cls.prototype);
return foo;
};
//so lets extend Type into newType
var newType = extend(Type);
//create an instance of newType and old Type
var t = new Type('bar');
var n = new newType('foo');
console.log(t);
console.log(t instanceof Type);
console.log(n);
console.log(n instanceof newType);
console.log(n instanceof Type);