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

前端 未结 8 511
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:41

    JavaScript allows functions to be treated as objects--you can add a property to a function. How do you do the reverse, and add a function to an object?

    You appear to be a bit confused. Functions, in JavaScript, are objects. And variables are variable. You wouldn't expect this to work:

    var three = 3;
    three = 4;
    assert(three === 3);
    

    ...so why would you expect that assigning a function to your variable would somehow preserve its previous value? Perhaps some annotations will clarify things for you:

    // assigns an anonymous function to the variable "foo"
    var foo = function() { return 1; }; 
    // assigns a string to the property "baz" on the object 
    // referenced by "foo" (which, in this case, happens to be a function)
    foo.baz = "qqqq";
    

提交回复
热议问题