0

Say I have the following code:

function MyObject() {
    EventTarget.call(this);
}
MyObject.prototype = new EventTarget();
MyObject.prototype.constructor = MyObject;      
MyObject.prototype.foo = someFunction; 
MyObject.prototype.bar = someOtherFunction

Is there a neat way to avoid defining MyObject.prototype.something = something in each line.

Do I have to define two objects and merge them? or is there some cleaner way to do the same thing?

algorithmicCoder
  • 6,595
  • 20
  • 68
  • 117

1 Answers1

0

Declare the functions inside the controller and you won't have to attach them to the prototype. Is this what you were after?

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/

See the various links mentioned in this answer: Extending an Object in Javascript

Community
  • 1
  • 1
S McCrohan
  • 6,663
  • 1
  • 30
  • 39
  • There are advantages to putting shared members on the prototype that you loose when declaring them as instance specific. Functions foo and bar won't change per instance yet every instance has one. http://stackoverflow.com/a/16063711/1641941 – HMR Jan 10 '14 at 04:59