1

I have written following code

1.

function Car() {
  this.make = "BMW"
}

var x = new Car().make
alert(x)

Result: shown alert BMW

2.

function Car() {
  this.make = "BMW"
}

var x = Car().make //removed new keyword
alert(x)

Result: did not show alert BMW. Error in console "Cannot read property 'make' of undefined"

3.

function Car() {
  this.make = "BMW"
  return this      //added return
}

var x = Car().make //removed new keyword
alert(x)

Result: shown alert BMW

Can anybody explain, what exactly happening, when I return 'this' ...?

1 Answer 1

2

When you call Car() (without the new operator), inside the function, this refers to the global context (e.g., window if you are in a browser). When you return this;, you are returning the global object. You should also find that your function set the make property of the global object to "BMW" (that is, alert(Car().make) followed by alert(make) should alert the same thing twice. Without return this; the default return value from a function is undefined.

When you use the new operator, a new object is created and bound to this inside the function while it is executing. The new operator return whatever the constructor returns, or the new object if the construction does not return anything. For more info about this, see the docs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.