手写New和instanceof

手写New和instanceof

New

new运算符创建一个用户定义的对象类型的实例,或者是具有构造函数的内置对象的实例

New的使用

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

const car1 = new Car('Eagle', 'Talon TSi', 1993);

console.log(car1.make);
// expected output: "Eagle"

手写New

function myNew(Fn,...args) {
    let obj = {}
    let result = Fn.call(obj,...args)
    //如果Fn构造函数返回的值是一个对象,myNew就返回这个对象
    if(result instanceof Object) return result
    obj.__proto__ = Fn.prototype
    return obj
}

function Person(name,age) {
    this.name = name
    this.age = age
    // return  {m:1,n:2}
}
let w = myNew(Person,'jiang',10)
console.log(w)

instanceof

instanceof用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上

instanceof的使用

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car);
// expected output: true

console.log(auto instanceof Object);
// expected output: tru

手写instanceof

function Person(name,age) {
    this.name = name
    this.age = age 
}
function myInstanceOf(obj,Type){
//temp等于obj的原型对象
    let temp = obj.__proto__
    //因为Object.prototype.__proto__的原型对象为null
    while(temp){
        if(temp === Type.prototype){
            return true
        }
        //顺着原型链去更改temp的值
        temp = temp.__proto__
    }
    return false
}

let p = new Person()
console.log(myInstanceOf(p,Person))//true
console.log(myInstanceOf(p,Object))//true
console.log(myInstanceOf(p,Function))//false
上一篇:Java关键字_____instanceof


下一篇:Java 14 令人无解的5大特性