说我有以下代码:
function MyObject() {
EventTarget.call(this);
}
MyObject.prototype = new EventTarget();
MyObject.prototype.constructor = MyObject;
MyObject.prototype.foo = someFunction;
MyObject.prototype.bar = someOtherFunction
是否有一种简洁的方法可以避免在每一行中定义MyObject.prototype.something = something
。
我是否必须定义两个对象并合并它们?还是有一些更清洁的方法来做同样的事情?
答案 0 :(得分:0)
声明控制器内的函数,您不必将它们附加到原型。这就是你追求的目标吗?
function EventTarget() {
this.baz = function() {console.log("baz")};
this.foobar = "foobar";
}
function MyObject() {
EventTarget.call(this);
this.foo = function() {console.log("foo")};
this.bar = function() {console.log("bar")};
}
MyObject.prototype = new EventTarget();
MyObject.prototype.constructor = MyObject;
thisObject = new MyObject();
thisObject.foo(); // outputs 'foo'
thisObject.bar(); // outputs 'bar'
thisObject.baz(); // outputs 'baz' via inheritance
console.log(thisObject.foobar); // outputs 'foobar' via inheritance
请参阅此答案中提到的各种链接:Extending an Object in Javascript