Search code examples
javascriptfunctioncall

How can create own call function in javascript?


As of my knowledge, in javascript there are three concepts; call, apply and bind I want to create these function with similar behavior.


Solution

  • Add your own call function like "_call"

    Function.prototype._call = function(newcontext, ...arg){
    
    var demoFn = new Function('tempfuncton', 'tempthis','arg' , '{ tempthis["f"]=tempfuncton; return tempthis.f(arg);}');
    demoFn(this,newcontext,arg);
    }
    

    write a demo function

    function anyfunction(args){
    console.log(this,args)
    }
    

    call it like previous. First argument should be an object. Otherwise write a code to convert it into object.

    anyfunction._call({'mm':'my provided this object'},"arg1","arg2")