Understanding this in different context

In constructor

① The new object is used as the this binding for the function call, so that we could add key-value pair like this.name = "abc" and the new object has been linked to the function’s prototype.

function Student(name, id) {
  console.log(this) // Student {}
  this.name = name; // Student { name: 'abc'}
  this.id = id;     // Student { name: 'abc', id: 1234}
}

const student = new Student("abc", 1234)

new operator turns function call into a constructor call which returns a new object;


② No return statement, constructor automatically return this;

③ Explicitly return an object. We will lost the newly created object with abc,1234, because no reference to it.

But return another object is not commonly usage.

function Student(name, id) {
  this.name = name;
  this.id = id;   
  // return null;
  return {
    name: "xyz",
    id: 666
  }
}
const student = new Student("abc", 1234)

④ In development environment, return Proxy to alert users when then use object incorrectly.

function Student(name, id) {
  this.name = name;
  this.id = id;   
  return new Proxy (this, {
    get(target, name) {
      //...
    }
  });
}
const student = new Student("abc", 1234)

⑤ Return anything else in constructor, JavaScript engine will ignore it but return the newly created object.

function Student(name, id) {
  this.name = name;
  this.id = id;
  return null;
}
const student = new Student("abc", 1234)
// return  {name: "abc", id: 1234}


Related Posts