Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the principle of new operator in JavaScript (graphic tutorial)

亚连
Release: 2018-05-21 10:39:19
Original
1748 people have browsed it

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;

}
Copy after login

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 tips


Detailed code explanation How to implement quick sorting in JavaScript


How to avoid re-rendering in React_javascript tips


The 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template