问题
function myFunc(){
console.log(myFunc.message);
}
myFunc.message = "Hi John";
myFunc();
Executing the above results in -
Answer: 'Hi John'
How is the function myFunc
have the property message
on it? typeof myFunc
results in "function" and console.log(myFunc)
displays the function content (without the property message
on it).
How does the above work? Is a function in JavaScript internally an object?
Note - I am aware that functions have other parameters like prototype and length on them. But I am not sure how these are implemented as well.
Additional query -
Since console.log(myFunc)
does not show the object properties, how do I list all the properties of a function object?
回答1:
How does the above work? Is function in javascript internally an object?
Yes
function example() {};
console.log(example instanceof Object);
回答2:
Yep, they are objects.
See in particular:
Every JavaScript function is actually a Function object. This can be seen with the code
(function(){}).constructor === Function
which returnstrue
.
回答3:
In JavaScript functions are first class objects. This is evidenced by the fact you can assign a function to a variable, pass it as an argument, add properties to it, add it as a property or member of an array etc etc. Sky is the limit.
var myFunction = function(passedFunction){
passedFunction();
console.log(myFunction.message);
};
let functionsArray = [myFunction, function() {
myFunction.message = "Hello World";
}];
functionsArray[0](functionsArray[1]);
The above outputs "Hello World"
Part of the reason this can seem weird may be in the way functions can be declared. In order to behave a bit like C (but not really) or other languages where a function is in some manner defined prior to the execution of the code proper, the naked 'function' statement 'hoists' the function declaration. So where you use this syntax:
myFunction();
function myFunction(){
console.log("Hello world");
}
What is actually happening is that your function declaration is being 'hoisted' to act as if it was this:
let myFunction = function(){
console.log("Hello world");
}
myFunction();
These two code snippets above are fundamentally equivalent in JavaScript. (N.b. var
declarations are also hoisted but let
and const
are not)
MDN has more about the function declaration and function hoisting.
回答4:
According to MDN, definition of function is:
In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.
So here by doing myFunc.message
you are adding an additional property to myFunc
function( or object) and then it is accessible inside function like other objects.
来源:https://stackoverflow.com/questions/51784263/how-do-javascript-functions-have-properties-in-them