Js inheritance is always not understood, know the new operation after finally understand the point.Juejin. Cn/post / 684490… www.jianshu.com/p/66f3aef3e… Github.com/mqyqingfeng…

1. Why is new needed

When learning c++, we know that new is to save code to mass produce objects. After learning some js, we know that new can not only save code, but also save memory.

// constructorfunction Person(name, age, job) {
    this.name = name;
    this.age = age;
    this.job = job;
    this.friends = ["Shelby"."Court"]; } // Person. Prototype = {sayName:function() {
        returnthis.name; }} person1 = new person (); person1 = new person ();"Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");
Copy the code

2. What did New do

Person1 example

  1. Create (or construct) a brand new object.
person1 = {}
Copy the code
  1. The new object will be connected by the implementation [[prototype]].
person1.__proto__ = Person.prototype
Copy the code
  1. This new object is bound to the function call’s this.
Constructor.apply(person1, arguments);
Copy the code
  1. If the function returns no other object, the function call in the new expression automatically returns the new object
return person1
Copy the code

3. How to implement a new operation

function objectFactory() {

    var obj = new Object(),

    Constructor = [].shift.call(arguments);

    obj.__proto__ = Constructor.prototype;

    var ret = Constructor.apply(obj, arguments);

    return typeof ret === 'object' ? ret : obj;

};
Copy the code

Because maybe the constructor has a return value in it (returns an object)