Assigning a Function to a Function Object's Property

72 views Asked by At

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();
1

There are 1 answers

0
Bergi On BEST ANSWER

That works totally fine:

myFuncObj = new function() {
    this.changeHandler = undefined;
};

myFuncObj.changeHandler = function(a, b) {
    console.log({a:a,b:b});
}

> myFuncObj
[-] Object 
 + changeHandler Function
 [-] Object
  + constructor Function
  [-] Object
> myFuncObj.changeHandler(1, 2)
[-] Object 
 + a: 1
 + b: 2
 [-] Object

Except that you never should use new function() { … }. Just do

var myFuncObj = {
    changeHandler: undefined;
};
myFuncObj.changeHandler = function(a, b) {
    console.log({a:a,b:b});
};

or

var myFuncObj = {
    changeHandler: function(a, b) {
        console.log({a:a,b:b});
    }
};