I have a JavaScript function object defined like this:
var minimal = (function() {
var handler = undefined;
var test = function() {
console.log(typeof handler);
if (typeof handler === 'function') {
handler();
}
};
var API = {
handler: handler,
test: test
};
return API;
}());
I want to be able to inject a function into the object at will.
When I set a function into that property, the function isn't being assigned to the object property, it still shows as undefined
:
minimal.handler = function() {
console.log('handled');
};
minimal.test();
Am I simply going about it all wrong? Is there a better pattern that I should be using?
SOLUTION
After reading the comments and responses, I realized that the issue was that I was overwriting the value in the API
object: not setting the object's handler variable. This is a minimal working example:
var minimal = (function() {
var handler = undefined;
var test = function() {
console.log(typeof handler);
if (typeof handler === 'function') {
handler();
}
};
var setHandler = function(func) {
handler = func;
};
var API = {
setHandler: setHandler,
test: test
};
return API;
}());
minimal.setHandler(function() {
console.log('handled');
});
minimal.test();
That works totally fine:
Except that you never should use
new function() { … }
. Just door