Constructors should not normally return. If there is a return, there is a return value type and a return reference type

Let’s start with the basic code

function Person(name) {
  this.name = name;
  // return 1; Case 1: return value type
  // return { name: 'Error' }; // Case 2: return reference type
}
const p = new Person('xm')
Copy the code

Printing this p separately yields two cases:

  1. Non-return and return value types are the first case.

    The result is the output Person {name: ‘xm’}, which is normal.

  2. The return reference type is the second case

    {name: ‘Error’}, which is the reference type of our return, will not be attached to the instance if we create the prototype method. TypeError will be reported when we call it.

Neither the prototype nor the returned value is what we expect, naturally thanks tonewThe credit for

So let’s simulate a new and see what happens when we create a new constructor

function New(Func, ... rest) {
  // 1. Create an empty object
  const obj = {};
  // 2. Point the pointer to the empty object to the prototype constructor
  obj.__proto__ = Func.prototype;
  // 3. Bind execution context this to the new object created above
  const result = Func.apply(obj, rest);
  // 4. If the constructor returns a value of "reference type", return it. Otherwise return the object created above
  return result instanceof Object ? result : obj;
}
Copy the code

The obvious answer is yesnewIs determined by the return type of the constructor

Let’s use our simulation implementationNewLet’s try and make a mistake

function Person(name) {
  this.name = name;
  return { name: 'Error' }; // return reference type
}
const p = New(Person, 'xm')
console.log(p);

Person.prototype.sayName = function() {
  console.log('My name:'.this.name);
}
p.sayName(); 
Copy the code
  • Error:TypeError: p.sayName is not a function

Another caveat: prototype methods should avoid using arrow functions: arrow functions are not bound to this and cannot get properties and methods on instance objects

conclusion

inJavaScriptIn the constructor:

  • If the return value is of a type, then the constructor has no effect and the instantiated object returns normally.
  • If a return references a type (array, function, object), the instantiated object returns that reference type