-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_function_are_object.js
More file actions
41 lines (33 loc) · 2.47 KB
/
Copy path02_function_are_object.js
File metadata and controls
41 lines (33 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Topic: Function are object
// Q. What is meant by "Functions are Objects" in JavaScript?
// -> In JavaScript, a function is a special type of object. It's not just a block of code that executes; it also has properties and methods, just like regular JavaScript objects. You can think of a function as an object that is also callable.
// Q. Why are functions treated as objects?
// -> Treating functions as objects provides several powerful capabilities:
// -> First-Class Citizens: This is the most important reason. It means functions can be:
// -> Assigned to variables.
// -> Passed as arguments to other functions (callbacks).
// -> Returned from other functions (higher-order functions).
// -> Stored in data structures (arrays, objects).
// -> Adding Properties: You can attach custom properties to a function, just like you can with any object. This allows you to associate metadata or related values directly with the function.
// -> Methods: Functions also have built-in methods like call(), apply(), and bind(), which are crucial for controlling how a function is executed and what this value it uses.
// -> Prototype: Every function in JavaScript has a prototype property (which is itself an object). This is the foundation of JavaScript's prototypal inheritance. Objects created using the new keyword with a function (as a constructor) will inherit properties and methods from this prototype object.
// Q. How are functions created as objects?
// -> When a function is created, the JavaScript engine creates a function object. This object contains:
// -> The executable code of the function.
// -> A set of built-in properties (like name, length, and prototype).
// -> Internal methods that handle how the function is called and behaves.
// Note:
// -> While functions behave like objects, there's a subtle distinction. They have an internal [[Call]] method that allows them to be executed, which regular objects don't have. The typeof operator reflects this special nature by returning "function" for functions, even though they are fundamentally objects.
// -> To see function as a object use `console.dir(function_name)`. It will show all the properties of that function in object form
// Example:
function function1() {
console.log(`Hello, World!`);
}
// Adding a property to the function object
function1.key1 = "value1";
console.log(function1.key1);
// Adding a method to the function object
function1.method = function () {
console.log(`I am a method`);
};
function1.method();