Search code examples
javascriptprototype-programming

Javascript object's prototype property


I have a question about prototype object.

I learned that constructor function has prototype property (not [[prototype]] property) and it indicates prototype object.

ex) If function's name is Person, prototype object's name will be Person.prototype

So I typed this code below.

function Person(name) {
    this.name = name;
}

var foo = new Person('foo');

console.dir(Person);

If my thought is right, Person function's prototype property has to point Person.prototype but actual result is different.

screenshot of my browser

But my book says:

photograph of my book

Why is Person.prototype's name 'Object' ??? I don't know why... My mental is going to be broken...

Someone please answer.. :(


Solution

  • Your Person() function has a prototype property. Person().prototype is called Object because it is indeed an object. In console, it is purely saying that the prototype property is an object.

    Because of the constructor name, it displays Person, possibly because the author used a different JavaScript/Browser version, or another version entirely. The 'Object' that you get is normal, and your code should work normally. You can ignore the difference.

    A function's prototype property is to allow you to add properties to your code. Here is an example:

    function Person(name, age, id) {
      this.name = name;
      this.age = age;
      this.id = id;
    }
    
    var me = new Person("Brian", 12, 0);
    

    Then later on in the code if you want to add a property to the person function, like my favorite programming languages:

    Person.prototype.favLanguages = null;
    

    When you want to define my favorite languages you can do:

    me.favLanguages = ['JavaScript', 'Java', 'HTML', 'CSS'];