How inheritance and Prototype Chain works in JS

52 views Asked by At

Have a look on my code. I don't understand how It's working

function doSomething() {
  this.testProp = 'testProp';
}

doSomething.testProp1 = "testProp1";
var doSomeInstancing = new doSomething();

console.log("doSomething.testProp:" + doSomething.testProp);
//undefined
console.log("doSomething.testProp1:" + doSomething.testProp1);
//testProp1
console.log(doSomething.hasOwnProperty('testProp1'));
//true 

console.log("doSomeInstancing.testProp:" + doSomeInstancing.testProp);
//testProp
console.log("doSomeInstancing.testProp1:" + doSomeInstancing.testProp1);
//undefined   
console.log(doSomeInstancing.hasOwnProperty('testProp1'));
//false

The question is why testProp is undefined in doSomething and not in doSomeInstancing and vice versa for testProp1.

1

There are 1 answers

0
Mark On BEST ANSWER

You are dealing with two distinct objects here:

the function: doSomething the object: doSomeInstancing

Both are objects and both can have properties. doSomeInstancing is the object returned from the function when you call new doSomething() and it is what this refers to in the body of the function. Adding properties to this object has no effect on the other object, the doSomething function. The opposite is also true.

If you are trying to inherit a property, you are actually looking for a third object: doSomething.prototype. This is a property of functions that points to an object that instances will be linked to. doSomeInstancing will inherit from this object to in the prototype chain. For example:

function doSomething() {
  this.testProp = 'testProp';
}

doSomething.prototype.testProp1 = "testProp1 value"

let p = new doSomething()

// p's parent in the protoype chain is doSomething.prototype
console.log(Object.getPrototypeOf(p) === doSomething.prototype)

console.log(p.testProp)
console.log(p.testProp1)