1. 程式人生 > >JS——new原理

JS——new原理

通過new建立物件經歷4個步驟

1、建立一個新物件;[var o = {};]

2、將建構函式的作用域賦給新物件(因此this指向了這個新物件);[Person.apply(o)] [Person原來的this指向的是window]

3、執行建構函式中的程式碼(為這個新物件新增屬性);

4、返回新物件。

一、建構函式和原生new操作符

function Person(name, age, job) {
        this.name = name;
        this.age = age;
        this.job = job;
        this.sayName = function () {
            alert(this.name);
        };
    }
    let person1 = new Person("yan",23,"stu");
    let person2 = new Person("sun",23,"stus");
    console.log(person1.__proto__ === person2.__proto__);//true
    console.log(person1.__proto__ === Person.prototype);//true
    console.log(Person.prototype.constructor === Person);//true
    //因此person1.__proto__ = person2.__proto__ = Person
    console.log(person1.name);//yan

二、建構函式和自己實現的New

function Person(name, age, job) {
        this.name = name;
        this.age = age;
        this.job = job;
        this.sayName = function () {
            alert(this.name);
        };
    }

let New = function (P) {
        let o = {};
        let arg = Array.prototype.slice.call(arguments,1);
        
        o.__proto__ = P.prototype;
        P.prototype.constructor = P;
       
        P.apply(o,arg);
        
        return o;
    };
    let p1 = New(Person,"Ysir",24,"stu");
    let p2 = New(Person,"Sun",23,"stus");
    console.log(p1.name);//Ysir
    console.log(p2.name);//Sun
    console.log(p1.__proto__ === p2.__proto__);//true
    console.log(p1.__proto__ === Person.prototype);//true

結合通過new建立物件經歷4個步驟和上面的New函式理解一下。