0

Example taken from here: http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/

I also asked a similar question here: Javascript: Added function does not appear on parent object.

Create an object

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

Add an attribute as a prototype. The new kind attribute does not appear on the object.

>Person.prototype.kind = 'person'

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

Now create a new object using the parent as the prototype. The added attribute is visible.

var zack = new Person('Zack');

Person {name: "Zack", kind: "person"}

Why is the added kind attribute not visible on the parent Person object, even though it can convey it to children?

Community
  • 1
  • 1
port5432
  • 5,889
  • 10
  • 60
  • 97
  • 1
    What is exacly your problem? it's not quite clear. What result did you expect? – Joel Harkes Oct 21 '14 at 13:11
  • My question is why cannot I see the added attribute on the original parent object. – port5432 Oct 21 '14 at 13:12
  • I'm confused. Why/how do you expect `Person` to change? The prototype object only effects the objects *created* by the constructor function, not the function itself. Mutating the prototype object does not magically change the constructor function. Maybe this helps: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript . FYI `function Person` does not create an object (like you mean it). It creates a constuctor function which lets you create objects. – Felix Kling Oct 21 '14 at 13:18
  • So the prototype object (Person + kind) is different from the constructor function? How can I see all the attributes of a prototype? (ie: like a class + superclass in other languages) – port5432 Oct 21 '14 at 13:23
  • 1
    `console.dir(Func.prototype)` . If you also want to see *instance properties*, you have to create an instance: `console.dir(new Func())`. The prototype object is the object shared by all instances created by the constructor function. It's their "prototype". – Felix Kling Oct 21 '14 at 13:42

2 Answers2

2

This is beceause Person is just a funtion(object)/Constructor:

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

To Get the kind object on person refer to the prototype

Person.prototype =
Person {kind: "person"}

Im not an expert in this but if you would want to create a new constructor you should overwrite the function.

You could see the function (below) as an constructor to set instance specific variables

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

Person.prototype.kind = 'person' is like a static variable on the class

Joel Harkes
  • 10,975
  • 3
  • 46
  • 65
1

You are looking at the Person Constructor.

To look at the properties of the definition of a Person you can use Object.getOwnPropertyNames(Person.prototype)

This would show the kind property.