1

If I create a new "Foo" and use the "addEventListener" method on it, it affects Foo's prototype and all new instances of Foo.

Simple example: http://jsfiddle.net/TYkF2/

function Foo() { }

Foo.prototype = {
  _evt: { open: [], close: [] },
  addEventListener: function(name, handler) {
    if (name in this._evt) {
      if (!(this._evt[name].indexOf(handler) > -1)) {
        this._evt[name][this._evt[name].length] = handler;
      }
    }
  },
  dispatchEvent: function(name, data) {
    data = data || {};
    if (name in this._evt) {
      for (var i = 0; i < this._evt[eventName].length; i++) {
        this._evt[name][i].call(this, data);
      }
    }
  }
};

var a = new Foo();

a.addEventListener("open", function() { alert("Hey!"); });
a.dispatchEvent("open");

var b = new Foo();

b.dispatchEvent("open"); // alerts Hey

alert(Foo.prototype._evt.open); //shows a's event handler
2
  • I think you forgot to ask the actual question? Commented Jan 15, 2014 at 12:44
  • First paragraph :) "If I create a new "Foo" and use the "addEventListener" method on it, it affects Foo's prototype and all new instances of Foo." Commented Jan 15, 2014 at 12:45

1 Answer 1

2

As _evt: { open: [], close: [] } is inside the prototype, a._evt and b._evt are actually the same object. If you put _evt in the constructor, it works as expected:

function Foo() {
    this._evt = { open: [], close: [] };
}
Sign up to request clarification or add additional context in comments.

2 Comments

How would I get this._evt if I where to create a third variable via Object.create(Foo.prototype)?
Nevermind, I moved the constructors contents into a new method that makes all the objects, and made the constructor call the new method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.