In JavaScript, an instance object can be created through the new operator, and this instance object inherits the properties and methods of the original object. Therefore, the significance of new's existence is that it implements inheritance in JavaScript, not just instantiates an object.
Let us first understand the role of new
through examples. The examples are as follows:
function Person(name) { this.name = name } Person.prototype.sayName = function () { console.log(this.name) } const t = new Person('小明') console.log(t.name) // 小明 t.sayName() // 小明
From the above examples we can draw The following conclusion:
new
The instance object created through the constructorPerson
can access the properties in the constructor.
new
The instance created through the constructorPerson
can access the properties in the constructor prototype chain, that is, throughnew
Operators, instances and constructors are connected through the prototype chain.
Constructor Person
does not explicitly return
any value (default returns undefined
), if What happens if we make it return a value?
function Person(name) { this.name = name return 1 } const t = new Person('小明') console.log(t.name) // 小明
The constructor in the above example returned 1
, but this return value is of no use, and the result is exactly the same as the previous example. We can draw another conclusion:
If the constructor returns the original value, then the return value is meaningless.
Let’s try what happens when the object is returned:
function Person(name) { this.name = name return {age: 23} } const t = new Person('小明') console.log(t) // { age: 23 } console.log(t.name) // undefined
Through the above example, we can find that when the return value is an object, the return value will be returned normally. go out. We once again came to a conclusion:
If the return value of the constructor is an object, then the return value will be used normally.
Summary: These two examples tell us that constructors should try not to return values. Because returning the original value will not take effect, returning the object will cause the new operator to have no effect.
First of all, we need to know what js does when using the new
operator:
After knowing the steps, we can start to implement the function of new:
function _new(fn, ...args) { const newObj = Object.create(fn.prototype); const value = fn.apply(newObj, args); return value instanceof Object ? value : newObj; }
The test example is as follows:
function Person(name) { this.name = name; } Person.prototype.sayName = function () { console.log(this.name); }; const t = _new(Person, "小明"); console.log(t.name); // 小明 t.sayName(); // 小明
The above is about the role of the new operator in JavaScript and how to implement a new operator.
The above is the detailed content of Do you know what js does when new an object?. For more information, please follow other related articles on the PHP Chinese website!