Bill
Bill

Reputation: 19328

Javascript prototype question on the `new` keyword

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    console.log(this)
}

const test = new Person(); //A
const test1 = Person(); //B

Question:

if i run both function, the first function (A) will return:

Person {firstName: undefined, lastName: undefined, age: undefined, eyeColor: undefined}

but when i run the function (B) it return window object

is the new keywords doing this?

function Person(first, last, age, eyecolor) {
    this = Object.assign(Person);
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    return this;
}

hence i don't see the window object? can someone explain and help on this please.

thanks

Upvotes: -1

Views: 72

Answers (2)

Mazaher Bazari
Mazaher Bazari

Reputation: 421

When you call a function this refer to caller. In your code caller is windows object. In the other hand, when you use new keyword, this create a new object and set it's prototype equal to master, means object.

Upvotes: 1

Nicholas Tower
Nicholas Tower

Reputation: 85211

Yes, that's roughly correct. The new keyword creates a new object, sets Person.prototype to be that object's prototype, and then invokes Person, with this set equal to the newly created object. If your function does not explicitly return anything, then the newly created object will be implicitly returned (and that's typically the behavior you want for a constructor, so i recommend omitting a return statement).

You can read more about the new operator here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

Upvotes: 1

Related Questions