How the new Operator Works
# How the new Operator Works
When using the new operator, the function that follows it executes the following steps in order:
- Create an empty object that will serve as the instance to be returned.
- Set the prototype of this empty object to point to the constructor's
prototypeproperty. - Assign this empty object to the
thiskeyword inside the function. - Execute the code inside the constructor.
- If the constructor has a return value and it is an object type, return that object; otherwise, return the instance object created above.
// Constructor
function Person(name,age){
this.name = name
this.age = age
}
// Custom _new
function _new() {
// Convert the arguments object to an array
var args = [].slice.call(arguments);
// Extract the constructor
var constructor = args.shift();
// Create an empty object that inherits the constructor's prototype property
var context = Object.create(constructor.prototype);
// Execute the constructor, assigning the context object to the internal this
var result = constructor.apply(context, args);
// If the result is an object, return it directly; otherwise, return the context object
return (typeof result === 'object' && result != null) ? result : context;
}
// Custom _new2
function _new2(/* constructor */ constructor, /* constructor params */ params) {
// Create an empty object that inherits the constructor's prototype property
var context = Object.create(constructor.prototype);
// Execute the constructor, assigning the context object to the internal this
var result = constructor.apply(context, params);
// If the result is an object, return it directly; otherwise, return the context object
return (typeof result === 'object' && result != null) ? result : context;
// (If the user defines a custom return object inside the constructor, use that object; otherwise, return context)
}
// Create an instance via custom _new
var actor = _new(Person, 'Zhang San', 28);
console.log(actor.name) // Zhang San
// Create an instance via custom _new2
var actor2 = _new2(Person, ['Li Si', 29]);
console.log(actor2.name) // Li Si
// Create an instance via the new operator
var actor3 = new Person('Wang Wu',30)
console.log(actor3.name) // Wang Wu
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
42
43
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
42
43
Edit (opens new window)
Last Updated: 2026/03/21, 12:14:36