JS实现new、instanceof方法

new

new的操作发生了什么呢?

new不过就是让我们从构造函数那里继承它的属性和他的原型属性

所以实现起来就分几步就好了

  • 创建一个空对象,将它的引用赋给 this,继承函数的原型
  • 通过 this 将属性和方法添加至这个对象
  • 最后返回 this 指向的新对象,也就是实例(如果没有手动返回其他的对象)
function mynew(parent,...args){
    if(typeof parent !=='function')
    throw 'it is not function'

    //创建一个parent的空对象 同时把实例和构造函数相连接
    let child =Object.create(parent.prototype)
    
    //修改this指向 完成传参
    let newofn=parent.apply(child,args)

    console.log(newofn);

    //是否返回了函数或者对象 返回了则直接return返回的函数 如果没有返回则手动返回这个构造函数 
    return( typeof newofn==='function'||typeof newofn==='object')?newofn:child
}   

测试代码

//不返回值的情况
function testfn(name='xixi'){
    this.name=name
    this.age=20
}

//创建实例
let a=mynew(testfn,'myfan')

console.log(a); //指向testfn 是testfn的实例

console.log(a.name);  //myfan
console.log(a.age);  //20


//需要满足
console.log(a instanceof testfn);  //true
console.log(a.constructor==testfn); //true
console.log(a.__proto__ ==testfn.prototype); //true

实例2

//返回值的情况
function testfn(name='xixi'){
    
   return {
       name,
       age:200
   }

}

console.log(a);  //{age: 200 name: "myfan"}
console.log(a.name);  //"myfan"
console.log(a.age);   //200

instanceof

__proto__指向构造函数的原型

思路就是递归,一直到__proto__为空为结束条件,向上查找是否和构造函数能对上

function myinstanceof(a,b){
    
    let left=a.__proto__
    let right=b.prototype

    //找到最后都不是返回false
    if(left==null) return false
    //是它的构造函数就返回true
    if(left==right) return true

    //递归查找
    return myinstanceof(left,b)
}

实例

//实例1
a=new Object()
console.log(myinstanceof(a,Object));  //true

//实例2
function fan(){

}

function xi(){

}

fan.prototype= new xi()

let b=new fan()

console.log(myinstanceof(b,fan)); //true
console.log(myinstanceof(b,xi)); //true
console.log(b instanceof xi );  //true