new方法的两种重现

new 关键字法

let a=1,b=2,c=3;
    function fn(a,b,c){
    }
    function new1(fn,...str){
    	//1.创建一个空的简单JavaScript对象(即`{}`)
        let obj={};
        //2.为步骤1新创建的对象添加属性`__proto__`,将该属性链接至构造函数的原型对象 
        obj.__proto__=fn.prototype;
        //3.将步骤1新创建的对象作为`this`的上下文
        let result=fn.bind(obj)(...str);
        //4.如果该函数没有返回对象,则返回`this`
        return typeof result===('object'||'function'&&result!==null)?result:obj;
    }
    let fn1=new1(fn,a,b,c);
    console.log(Object.getPrototypeOf(fn1)===fn.prototype);

new fn()法

// 构造器函数
let Parent = function (name, age) {
    this.name = name;
    this.age = age;
};
Parent.prototype.sayName = function () {
    console.log(this.name);
};
//自己定义的new方法
let newMethod = function (Parent, ...rest) {
    // 1.以构造函数的prototype属性为原型,创建新对象;
    let child = Object.create(Parent.prototype);
    // 2.使用指定的参数调用构造函数,并将 `this` 绑定到新创建的对象
    let result = Parent.bind(child)(...rest);
    // 3.如果构造函数没有手动返回对象(引用类型),则返回第一步创建的对象(实例),否则返回手动设置的返回值
    return typeof result===('object'||'function'&&result!==null) ? result : child;
};
//创建实例,将构造函数Parent与形参作为参数传入
const child = newMethod(Parent, 'echo', 26);
child.sayName() //'echo';

//最后检验,与使用new的效果相同
child instanceof Parent//true
child.hasOwnProperty('name')//true
child.hasOwnProperty('age')//true
child.hasOwnProperty('sayName')//false
child.__proto__===Parent.prototype//true
posted @ 2022-03-24 14:45  听风小弟  阅读(54)  评论(0)    收藏  举报