How can I declare a variable as a function as well as assign values to it

I tried this:

 var fun = function(){ console.log("booyah"} , {
  hell: function(){
    console.log("hello");
  },
  boy: ()=>{
    alert("blah");
  }
};
fun.boy();

I want that first I call fun function and then Access functions I have stored as objects. But I am getting errors . How can I fix it? Or is there any other way to do that?
Please help.

28 thoughts on “How can I declare a variable as a function as well as assign values to it”

  1. Check the below code, reference taken from Can you create functions with custom prototypes in JavaScript?

    function MyFun() {
        if (!this || this==window) {
            return new MyFun();
        }
    
        var f = function() {
            return "thanks for calling!";
        }
        f.__proto__ = MyFun.prototype;
        f.constructor = MyFun;
    
        return f;
    }
    
    MyFun.prototype = {
        foo: function() {
            return "foo:" + this();
        },
        __proto__: Function.prototype
    };
    
    var f = new MyFun();
    alert("proto method:"+f.foo()); // try our prototype methods
    alert("function method:"+f.call()); // try standard function methods
    alert("function call:"+f()); // try use as a function
    alert('typeof:' + typeof f); // "function", not "object". No way around it in current js versions
    alert('is MyFun:' + (f instanceof MyFun)); // true
    alert('is Function:' + (f instanceof Function)); // true
    Reply
  2. You can achieve this kind of result by editing the prototype of the function.

    Example:

    function foo() {
            const something = 'the thing';
        
            return something;
        }
        
        const customPrototype = {
            greeting: (name) => {
                const greetingTemplate = `Hello ${name}`;
        
                return greetingTemplate;
            },
        
            randomNumber: () => {
                return Math.random();
            },
        };
        
        // Extending prototype to access our custom prototype functions
        Object.assign(foo, customPrototype);
        
        
        console.log(foo()); // the thing
        console.log(foo.greeting('People')); // Hello People
        console.log(foo.randomNumber()); // 0.26138311987993545
        // Default prototype functions are working as well
        console.log(foo.toString()); // [object Function]

    EDIT: Thanks to @Bergi for correcting me!

    Reply

Leave a Comment