Handwritten instanceof and new

Time:2021-2-24
Handwritten instanceof
Instanceof checks whether there is a prototype in the prototype chain of the target object that is the same as the prototype of the specified object,
Whether two prototypes are equal or not is determined by = = = strictly equal.
function myInstanceof(obj, obj2) {
    let proto = obj.__proto__;
    let prototype = obj2.prototype;
    let queue = [proto];
    //Loop obj prototype chain to obtain__ proto__  Compared with prototype
    while(queue.length) {
        let temp = queue.shift();
        if(temp === null) return false;
        if(temp === prototype) return true;
        queue.push(temp.__proto__);
    }
}

//Testing

myInstanceof(new Date(), Date);         // true
myInstanceof({}, Object);               // true
myInstanceof('Jason', Number);          // false
myInstanceof(23, Stirng);               // false
Handwritten NEW
Thinking:
    1. New f() the object created by the constructor__ proto__  Point to the prototype of the constructor
    2. This in f() constructor points to the instance object of f() constructor
function myNew(F){
    let result = {};
    let arg = Array.prototype.slice.call(arguments, 1);
    //The__ proto__  Point to f.prototype
    Object.setPrototypeOf(result, F.prototype);
    //This points to the instance object
    F.apply(result, arg);
   return result;
}

//Testing
function F(name, age) {
    this.name = name;
    this.age = age;
}

let user = myNew(F, "Jason", 23);
console.log(user.__proto__ === F.prototype);            // true