The principle of the new operator in JavaScript

Source: Internet
Author: User
Tags function prototype

JavaScript in the new is a syntactic sugar, for learning C++,java and C # and other object-oriented languages, think JS inside there are classes and objects of the difference, the implementation of JS and no class, everything is the object, more than Java to complete

New's process is actually to create a new object, the prototype of the new image is set to the constructor function prototype, in the process of using new, a total of 3 objects involved in the collaboration, the constructor function is the first object, the prototype object is two, the newborn into an empty object is a third object, and ultimately return an empty object, But this empty object is not a vacuum, but a reference that already contains a prototype (__PROTO__)

The steps are as follows:

(1) Create an empty object obj

(2) __proto__ the null object (ie does not have this attribute) member points to the prototype member object of the constructor

(3) using the Apply Call constructor function, this binds to an empty object on obj.

(4) Returns an empty object, obj

It is perfectly possible to write a function instead of using new, and 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 principle of the new operator in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.