How to convert an “object” into a function in JavaScript?

前端 未结 8 494
Happy的楠姐
Happy的楠姐 2020-12-01 08:53

JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the

相关标签:
8条回答
  • 2020-12-01 09:48

    It's easy to be confused here, but you can't (easily or clearly or as far as I know) do what you want. Hopefully this will help clear things up.

    First, every object in Javascript inherits from the Object object.

    //these do the same thing
    var foo = new Object();
    var bar = {};
    

    Second, functions ARE objects in Javascript. Specifically, they're a Function object. The Function object inherits from the Object object. Checkout the Function constructor

    var foo = new Function();
    var bar = function(){};
    function baz(){};
    

    Once you declare a variable to be an "Object" you can't (easily or clearly or as far as I know) convert it to a Function object. You'd need to declare a new Object of type Function (with the function constructor, assigning a variable an anonymous function etc.), and copy over any properties of methods from your old object.

    Finally, anticipating a possible question, even once something is declared as a function, you can't (as far as I know) change the functionBody/source.

    0 讨论(0)
  • 2020-12-01 09:48

    There doesn't appear to be a standard way to do it, but this works.

    WHY however, is the question.

    function functionize( obj , func )
    { 
       out = func; 
       for( i in obj ){ out[i] = obj[i]; } ; 
       return out; 
    }
    
    x = { a: 1, b: 2 }; 
    x = functionize( x , function(){ return "hello world"; } );
    x()   ==> "hello world" 
    

    There is simply no other way to acheive this, doing

    x={}
    x() 
    

    WILL return a "type error". because "x" is an "object" and you can't change it. its about as sensible as trying to do

     x = 1
     x[50] = 5
     print x[50] 
    

    it won't work. 1 is an integer. integers don't have array methods. you can't make it.

    0 讨论(0)
提交回复
热议问题