Let’s say I have the following code, which I CANNOT modify
var namespace = {};
function() {
var MyConstructorFunction = function() {
alert("default behavior");
};
namespace.MyConstructorFunction = MyConstructorFunction;
setTimeout(function() {
var instance = new MyConstructorFunction();
}, 1000)
}();
I would like to externally add some code in the global scope from which I only have access to namespace for making instance to be constructed with alert("custom behavior");
Just to clarify my intentions, let’s say I could think of these two aproaches:
namespace.MyConstructorFunction = function() {
alert("custom behavior");
};
or
namespace.MyConstructorFunction.prototype.constructor = function() {
alert("custom behavior");
};
But obviously they don’t work. Is there any way to do this?
You can use the prototype chain to override methods in a namespace.
And you can reuse the namespace token
Or you can use a different namespace if you would prefer.
Object.create is an ES5 feature which cannot be emulated entirely in ES3, but in this use case it should work with a basic polyfill.
But I understand you want to call a different constructor from the setTimeout, which in this example is impossible. The function references a local variable which cannot be altered. While you can change the global behaviour of an object like in this example, you cannot alter the variables inside a closure except through functions that can see those variables. If the function were to reference the globally scoped variable and not the locally scoped variable you would be in luck.
i.e: