You're misunderstanding the example you're representing. All instances of Sub
class get the name
property, on the contrary no Base
class instance gets access to the name
property.
Have a careful look:
mySub = new Sub("rohita");
mySub.hi();
// since Sub class doesn't override the hi method, it falls back to the parent's one,
// thus this.name is valid for any instances of Sub class.. not of Base class,
// Base class instances doesn't really access the name property of Sub class..
// to prove this let's log out `this.name` for any instance of Base class,
// it'll be simply `undefined`, but for the Sub class, it's the one already defined by Sub class itself
myBase = new Base();
myBase.hi(); // => hello undefined // makes sense now, right?
How is this from base class able to access name property from sub
class in the hi function?
this
from Base
class doesn't really access the property of Sub
class, this.name
is clearly undefined
from Base
class in other word, any instance of Base
class.
Since Sub
class doesn't override the hi
method inherited from Base
class, invoking hi
on Sub
instance falls back to the parent one, in that context this
clearly refers the Sub
class, hence the name
property of it.