Now I will bring you a brief discussion on the principle of new operator in javascript. Let me share it with you now and give it as a reference for everyone.
New in JavaScript is a syntactic sugar. For those who have studied object-oriented languages such as C, Java and C#, they think that there is a difference between classes and objects in JS. In implementation, JS does not have classes. , everything is an object, and it is more thorough than Java. The process of new is actually to create a new object and set the prototype of the new object to the prototype of the constructor function. In the process of using new, there are Three objects participate in the collaboration. The constructor function is the first object, the prototype object is the second object, and the newly generated empty object is the third object. An empty object is finally returned, but this empty object is not vacuum. Instead, it already contains a prototype reference (__proto__)
The steps are as follows:(1) Create an empty object obj
(2) Let the __proto__ (IE does not have this attribute) member of the empty object point to the prototype member object of the constructor
(3) Use apply to call the constructor function, and this is bound to the empty object obj.
(4) Return the empty object obj
#It is also 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 is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to avoid re-rendering in React_javascript tipsDetailed code explanation How to implement quick sorting in JavaScriptHow to avoid re-rendering in React_javascript tipsThe above is the detailed content of Detailed explanation of the principle of new operator in JavaScript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!