Jax Logan
Jax Logan

Reputation: 15

Property inheritance involving objects and prototypes

I'm a newbie at JS and in one of my tests I've been trying to figure out how the following code works in terms of property inheritance.

function doSomething(){}

doSomething.prototype.foo = "bar"; //Add "foo" property to doSomething's prototype
let anInstance = new doSomething();
anInstance.prop = "value"; //Add "prop" property to object "anInstance"
doSomething.prop = "another value"; //Add "prop" property to "doSomething"
let anotherInstance = new doSomething();

console.log(doSomething.prop);
console.log(anInstance);
console.log(anotherInstance.prop);

This is the above script's output in the console:

another value

doSomething{prop: "value"}
  prop: "value"
  __proto__:
    foo: "bar"
    constructor: ƒ doSomething()
    __proto__: Object

undefined

As you can see, printing doSomething's prop property after being added to it returns expected another value, but accessing anotherInstance's prop returns undefined.

Isn't that anotherInstance supposed to "inherit" such prop property since it's defined within the function from which it was created?

Thanks in advance.

Upvotes: 1

Views: 48

Answers (1)

Mark
Mark

Reputation: 92440

Adding a property to a function is not the same as adding a property to the function's prototype object. Instances of the function inherit the function's prototype properties, not the function's own properties:

function doSomething(){}

doSomething.prototype.foo = "bar"; //Add "foo" property to doSomething's prototype

doSomething.prop = "another value"; //Add "prop" property to "doSomething" but no the prototype

let anotherInstance = new doSomething();

// only has foo:
console.log(doSomething.prototype)

// this is the object it will inherit from
// only has foo
console.log(Object.getPrototypeOf(anotherInstance))

//they are the same object:
console.log(doSomething.prototype === Object.getPrototypeOf(anotherInstance))

In the code above doSomething.prop is just a property of the function, it plays no role in prototype inheritance.

Upvotes: 1

Related Questions