Travis J
Travis J

Reputation: 82267

How can I overwrite a function inside of a closure?

Given:

(function() {
 function Foo() {
 }
 $.extend(Foo.prototype, {
  bar: 'hasBeer'
 });
})

Is it possible to change the bar method from outside of that closure?

Upvotes: 2

Views: 1092

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

If you have access to the constructor function (Foo) and you want to override bar for all instances, you assign a new value to Foo.prototype.bar.

If you have an instance of Foo, you can either only override bar for that instance:

instance.bar = ...;

or for all instances by, again, overriding the prototype method. For this you have to get the prototype first, which you can do with Object.getPrototypeOf [MDN]:

Object.getPrototypeOf(instance).bar = ...;

But note that this is an ES5 method and is not available IE <= 8 or Opera.


If you neither have access to the constructor, nor an instance, you cannot change the property, other than by modifying the source code.

Upvotes: 3

Related Questions