Handwriting New and instanceof

Handwriting New and instanceof

New

The new operator creates an instance of a user-defined object type, or an instance of a built-in object with a constructor

Use of 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"

Handwriting 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 is used to detect whether the prototype property of the constructor appears on the prototype chain of an instance object

Use of 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

Handwritten 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

Guess you like

Origin blog.csdn.net/rraxx/article/details/115014646