If I write a new, what does new do?

Did four things:

  • An empty object is created
  • Binding this value
  • Link to the prototype
  • Return a new object

Here’s an example:

function F(){

}

let o = new F();
Copy the code

Four things: 1. create an object let o = {} 2. bind this value f.call (o) 3. Link to prototype O._ _ proto_ = F.prototype 4. Return o

New is not supported after the function abbreviation, nor is new supported for arrow functions

Simulation implementation new

function create(){// Create an empty objectletobj = new Object(); // Get the constructorletConstructor = [].shift.call(arguments); // Link to obj.__proto__ = Constructor. Prototype; / / bind thisletresult = Constructor.apply(obj,arguments); // Return a new object,(if the return value is an object, otherwise return an instance object of the constructor)return typeof result === "object" ? result : obj;
}
Copy the code

test

function Test(name,age){
	this.name = name;
	this.age = age;
}

let Test1 = new Test("Fan", 20); console.log(Test1.name); // Fan console.log(Test1.age); / / 20let Test2 = create(Test,"Jun", 22); console.log(Test2.name); // Jun console.log(Test2.age); / / 22Copy the code

After testing, create() works

The principle of the new

function Person(name){
    this.name = name;
    return {
    }
}
Person.prototype.say = function(){
    console.log("say....")}function myNew() {let Constructor = [].shift.call(arguments) 
    let obj = {};
    obj.__proto__ =  Constructor.prototype
    let r = Constructor.apply(obj,arguments)
    return r instanceof Object ? r : obj;
}
let p = myNew(Person,"Fan")
console.log(p.name)
p.say()
Copy the code

^ _ <