Knowledge about

What happens if a function returns return {}, return null, return 1, return true?

The simple answer is to create a code and experiment with it

Code test

Practice is the mother of wisdom

console.table(
  [null.undefined.1.true."".Symbol(), { a: 1},1.2]]
    .map((v) = > [
      v,
      function () {
        return v;
      },
    ])
    .map(([ret, MyConstructor]) = > [
      Object.prototype.toString.call(ret),
      ret,
      new MyConstructor(),
    ])
);
​
Copy the code

Simulation function

function myNew(fn, ... args) {
  // Create an empty object
  const obj = {};
  // Link the __proto__ attribute of this object to the constructor prototype object
  obj.__proto__ = fn.prototype;
  // Call the constructor as this context and receive the return value
  const res = fn.apply(obj, args);
  The constructor returns the value if it exists and is a reference data type, otherwise the created object is returned
  return typeof res === "object" ? res : obj;
}
const c = myNew(Person, "b");
c.say();
Copy the code

conclusion

  • The base type returns an empty object
  • Reference type Returns the reference type

The interview guide

  • The base type returns an empty object
  • Reference type Returns the reference type

review

  • Again, one of the special things about Javascript that you should keep in mind.

Support but uncle

Pay attention to the public number [front-end bus] and Ran Uncle together