Aar*_*lla 6 javascript oop constructor
我有这个JavaScript:
var Type = function(name) {
this.name = name;
};
var t = new Type();
Run Code Online (Sandbox Code Playgroud)
现在我想添加这个:
var wrap = function(cls) {
// ... wrap constructor of Type ...
this.extraField = 1;
};
Run Code Online (Sandbox Code Playgroud)
所以我可以这样做:
wrap(Type);
var t = new Type();
assertEquals(1, t.extraField);
Run Code Online (Sandbox Code Playgroud)
[编辑]我想要一个实例属性,而不是类(静态/共享)属性.
在包装函数中执行的代码应该像我将它粘贴到真正的构造函数中一样工作.
类型不Type应该改变.
更新:这里有更新版本
你实际上在寻找的是将Type扩展到另一个类.在JavaScript中有很多方法可以做到这一点.我不是真的很喜欢new和prototype构建"类" 的方法(我更喜欢寄生继承风格),但这是我得到的:
//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);
Run Code Online (Sandbox Code Playgroud)