Function
1. What is a Function?
Let's make it simple. It is just one of an object.
A function consists of ‘name’, ‘argument’ and ‘expression’.
Normally we define a function using a literal expression.
function functionName(argument) {
// express what this funtion does
}
But we can also use a constructor.
Remind this:
- An object has Property and method
- A function is an object
- All objects are created by a constructor
First, function has default property 'length' and method 'toString()'.
functionName.length; // 1
functionName.toString(); // literal expression of this function
functionName.constructor; // ƒ Function() { [native code] }
Only an object has property and method, so we can see that function is an object.
Second, when you define a function using the literal expression, internally it calls constructor 'Function()' and returns an instance of Function.
You can also define a function using a Function constructor.
var sum = new Function('a', 'b', 'return a + b');
sum; //ƒ anonymous(a,b) { return a + b}
sum(2,4); // 6
2. What happens when you define a Function?
First, it delegates constructor to function
It is the reason that only function can use a keyword 'new' .
Be aware that there is no constructor inside the function.
The function is just delegated authority to call the constructor with keyword 'new'.
Second, it creates a Prototype and Prototype link.
What the hell is Prototype?
It is tremendously important in JS, but we will see it in the next post.
3. Appendix
In the previous post, I warned that do not confuse the primitive type 'Number' and 'Number' Object.
Here is why :
var n = 1; // it is the primitive type
Number; // constructor of Number Object
ƒ Number() { [native code] }
As the above result shows us, Number Object is a function.