在javascript中处理这个继承代码的简洁方法?

时间:2014-01-10 02:54:57

标签: javascript oop inheritance

说我有以下代码:

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

我是否必须定义两个对象并合并它们?还是有一些更清洁的方法来做同样的事情?

1 个答案:

答案 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

http://jsfiddle.net/kFUDy/

请参阅此答案中提到的各种链接:Extending an Object in Javascript