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 reverse, and add a function to an ‘object’?
This works:
var foo = function() { return 1; }; foo.baz = 'qqqq';
At this point, foo() calls the function, and foo.baz has the value ‘qqqq’.
However, if you do the property assignment part first, how do you subsequently assign a function to the variable?
var bar = { baz: 'qqqq' };
What can I do now to arrange for bar.baz to have the value ‘qqqq’ and bar() to call the function?
You can’t (as far as I know) do what you’re asking, but hopefully this will clear up any confusion.
First, most objects in Javascript inherit from the Object prototype.
Second, functions ARE objects in Javascript. Specifically, they are objects that inherit from the Function prototype, which itself inherits from the Object prototype. Check out Function on MDN for more information.
If you create a value that is an Object object first, you can’t (as far as I know) convert it to a Function object later. What you CAN do however is create a new function, copy the properties from your old object to this function, and then reassign that function to the same variable, discarding the old object.
You can quickly copy the properties of one object to another with
Object.assign(target, source).But this isn’t something you would typically do in practice. It’s generally not recommended to add properties to a standard object like functions in the first place.
Finally, anticipating a possible question, you can’t change the body of a function after it has been created. The function body is stored internally and not exposed as a property.