Home  >  Article  >  Web Front-end  >  A brief discussion on the principle of new operator in JS

A brief discussion on the principle of new operator in JS

怪我咯
怪我咯Original
2017-07-04 15:22:321366browse

The editor below will bring you a brief discussion on the principles of newoperator in javascript. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

new in javascript is a syntactic sugar. For those who have studied object-oriented languages ​​such as c++, java and c#, they think that in js There is a difference between classes and objects. In terms of implementation, js does not have classes. Everything is an object. 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 constructor The prototype of the constructor function. In the process of using new, a total of three objects participate in the collaboration. The constructor function is the first object, the prototype object is two, and a newly generated empty object is the third object. Finally, it returns is an empty object, but this empty object is not vacuum, but already contains a prototype reference (proto)

The steps are as follows :

(1) Create an empty object obj

(2) Let the proto member of the empty object (IE does not have this attribute) point to the constructor prototype member object

(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 the detailed content of A brief discussion on the principle of new operator in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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