New in javascript is a syntax sugar. For those who have learned object-oriented languages such as C++, java and c#, they think that there is a difference between classes and objects in js. There is no class in js, everything is an object, which is more thorough than java.
The process of new is actually to create a new object, set the prototype of the new image as the prototype of the constructor function. In the process of using new, a total of 3 objects participated in the collaboration. The constructor function is the first object, the prototype object is two, and a new empty object is the third object. The final return is an empty object, but this empty object is not vacuum, but already contains a reference to the prototype (__proto__)
The steps are as follows:
(1) Create an empty object obj
(2) Let the __proto__ (IE does not have this property) member point to the constructor's prototype member object
(3) Use apply to call the constructor function, and this is bound to the empty object obj.
(4) Return empty object obj
It is also perfectly possible to write a function yourself instead of using new. The sample code is as follows:
function NEW_OBJECT(Foo){var obj={};obj.__proto__=Foo.prototype;obj.__proto__.constructor=Foo;Foo.apply(obj,arguments)return obj;}The above article briefly discusses the principle of the new operator in JavaScript. It is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.