js模拟new, new 之后发生的事情

107 阅读1分钟
    function Person(name){
        this.name = name;
    }
    Person.prototype.getName = function(){
        return this.name;
    }

    function createObject(){
        // 创建一个对象
        var obj = new Object();
        // 获取构造器函数
        Constructor = [].shift.call(arguments);
        // new出来的对象的__proto__指向构造器函数的原型对象
        obj.__proto__ = Constructor.prototype;
        // 构造器内的this指向obj 设置对象的构造器属性
        Constructor.apply(obj,arguments);
        return obj;
    }

    var a = createObject(Person,'jack');
    var b = new Person("jack")
    console.log(a,b)