The foundation.

1. The new operator

new MDN

New: Creates an instance through the constructor.

1. The execution of the new operator

  • 1. Create an empty JavaScript object ({}).

  • 2. Link the constructor of this object to another object.

  • 3. Use the object created in Step 1 as the this context.

  • 4. If the function does not return an object, return this.

2. Write a new

function myNew(fn, ... rest) {
    const obj = Object.create(fn.prototype);
    const res = fn.apply(obj, rest);
    return res instanceof Object ? res : obj
}
Copy the code

2. The instanceof operator

instanceof MDN

1. The instanceof operator

Instanceof is used to check whether the stereotype of a constructor is on the stereotype chain of an instance.

2. The handwritten instanceof

// Write instanceof by hand, holding that the prototype of the instance is equal to the prototype of the constructor
function myInstanceof(left, Right) {
    left = left._proto_;
    Right = Right.prototype;
    while (true) {
        if (left === null) {
            return false;
        }
        if (left === Right) {
            return true; } left = left._proto_; }}Copy the code

The key to handwriting instanceof is to grasp that the prototype of the instance is equal to the prototype of the corresponding constructor.