Jonah
Jonah

Reputation: 16202

Confused about ykatz article on javascript constructors and prototypes

This question is inspired from this article by Yehuda Katz. The relevant portion is this:

In order to facilitate object oriented programming, JavaScript allows you to use a Function object as a combination of a prototype to use for the new object and a constructor function to invoke:

var Person = function(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

Person.prototype = {
  toString: function() { return this.firstName + ' ' + this.lastName; }
}

Here, we have a single Function object that is both a constructor function and an object to use as the prototype of new objects.

I am confused because it seems to me the Function object acting as the constructor and the prototype are different. This is clear from the following console output from chrome:

chrome console output

That is, the constructor function is the function object above with two arguments: firstName and lastName; whereas the prototype is just an ordinary object that happens to have one property (toString), which in turn is defined by the separate function object function() { return this.firstName + ' ' + this.lastName; }

Am I misunderstanding what he's saying, or is the article incorrect?

Upvotes: 0

Views: 90

Answers (1)

Esailija
Esailija

Reputation: 140220

Yes, that is incorrect. The prototype used for new objects is the one referenced by the .prototype property of the constructor function at the creation time of an object, which is a separate plain object from the constructor function.

function Person() {

}

var a = new Person(); //a.__proto__ is assigned Person.prototype

Person.prototype = {}; //This doesn't affect a, because .__proto__ was assigned at creation time

var b = new Person(); //b.__proto__ is assigned Person.prototype, which is just the random object we created with {}

Upvotes: 1

Related Questions