The function and difference of the new operator and Object.create () in JS

Source: Internet
Author: User
Tags es6 class

The function and difference of the new operator and Object.create () in JS

76785231

August 06, 2017 19:19:26Hits: 1058

First, the new operator

The mechanism of new in JavaScript is actually quite different from the class-oriented language.

In JavaScript, constructors are just some of the functions that are called when using the new operator. They do not belong to a class, nor do they instantiate a class. In fact, they are not even a special type of function, they are just ordinary functions called by the new operator.

Using new to invoke a function, or when a constructor call occurs, the following actions are performed automatically.
1. Create (or construct) an entirely new object.
2. This new object is connected to [[prototype]] ([[Prototype]]).
3. This new object is bound to this of the function call.
4. If the function does not return another object, the function call in the new expression will automatically return the new object.

Second, object.create

Calling Object.create (..) creates a "new" object in thin Air and associates [[Prototype]] inside the new object with the object you specify.

Using these two methods for prototype inheritance,

Perform a small experiment:

function A (id,name) {
this.id=5;
This.name=name;
This.sex= ' Nan ';

this.colors=[' red ', ' blue ';
}
A.prototype.speak=function () {
Console.log (this.id);
}
function B (id,name) {

A.call (This,id,name);
This.id=id;
This.name=name;
}
B.prototype=object.create (A.prototype);
B.prototype=new a ();//The constructor of a is called once using new, and 2 constructs are called when combined with the constructor technique, which is the first time
var test1=new B (3, ' test1 ');
var test2=new B (4, ' test2 ');
Test1.colors.push (' black ');
Console.log (test1.colors); ["Red", "Blue", "black"]
Console.log (test2.colors); ["Red", "Blue", "black"]
Console.log (test1.sex);//Use the object.create () result as undefined; use new to result in ' Nan '.
Test1.speak ();

As shown in the code above, there are some side effects when the prototype of object B is prototyped by the new A () method. The first: This adds Data property B to a This property can also be found through the [[Prototype]] chain, so this method modifies function A will directly affect its descendants (here is function B), the consequences are unthinkable.

Second: When using the prototype chain to implement inheritance, all the properties and methods of the prototype are shared by the instance, which is appropriate for the function, the attribute instance for the base type value can override the prototype, but for a property that contains a reference type value, the modification of each instance changes the properties of the prototype. Because a property of a reference type contains a pointer to a reference object (such as an array type). Thus, after the prototype is inherited, the prototype will actually become an instance of another type. As a result, the original instance attribute becomes the current prototype attribute. (such as the colors property in the instance object of B). This side effect is also present using the Object.create () method.

You can use the borrow constructor technique to solve this problem. The first line of the constructor of type B is written on A.call (this,id,name); the principle is that an instance of B has a property that has a reference type value and modifies the B instance without modifying its properties on the prototype.

Third: When you create an instance of a subtype, you cannot pass parameters to the super-type constructor. (In fact, there is no way to pass parameters to a super-type constructor without affecting all object instances).
Cause Analysis: See step 3rd of the new operation, which will be bound to the this object of the function call (equivalent to the Java language Instantiation object, which has an instance property of Class A). So when executing b.prototype=new A (); B.prototype has the id,name and sex attributes. The object test1 does not, and the sex attribute is found through the prototype chain when accessing Test1.sex.

The b.prototype changes before and after the new operation and the Create () operation are specified as shown. The left is the default prototype object of B, and after the new operation in the figure

The prototype object, and the graph right is the Create () operation after the B point prototype the object. It can be seen in common:
1, B has no b.prototype.constructor attribute, (in fact.) The constructor property is only a public and non-enumerable default when the B function is declared

property, if you create a new object and replace the default. prototype object reference for the function, the new object is not automatically obtained. Constructor genus

Of )
2, B's prototype chain has inherited a prototype, associated with a prototype method.

Then look at the Test1 object, the left is the new operation of the Test1 object prototype chain, the graph right is the object.create () operation after the prototype chain. Can clearly know why the former test1.sex can print out ' Nan ', the latter is undefined.

In addition, there are 1 common types of error practices associated with prototypes
B.prototype = a.prototype;//is not the same as the mechanism you want, this time it does not create a new object associated to A.prototype, it just lets

B.prototype directly refers to the A.prototype object. So when you directly execute an assignment statement like "b.prototype.sex= ...", it will be modified directly

The A.prototype object itself.

Therefore, the best way to create an appropriate association object is to Object.create (..) instead of the new A () with side effects. The only downside to doing this

Is the need to create a new object and then discard the old object (loss of performance: discarded objects need to be garbage collected), can not directly modify the existing

The default object.

This is just the best way to ES6 before, ES6 added auxiliary functions object.setprototypeof (..), you can modify the association in a standard and reliable way.

As shown, this method does not have to discard the default B.prototype and modify it directly.

ES6 class Inheritance Mode

[JavaScript]View PlainCopy
  1. Class C {
  2. Constructor (name, id) {
  3. this.name = name;
  4. this.id = ID;
  5. }
  6. Say () {
  7. Console.log (this.name)
  8. }
  9. }
  10. class D extends C {
  11. Constructor (name, ID, age) {
  12. super (name, id); //You must call the Super method here first
  13. this.age = age;
  14. }
  15. }
  16. Let ObD = new D (' MHT ', $)
  17. Obd.say ()
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. 76785231Personal Category: JavaScript

The function and difference of the new operator and Object.create () in JS

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.