When I use JavaScript prototype to inherit a object and want to use it's method in the following way:
var Father = {
name:'Father',
act:function(){
console.log('the name is '+this.name);
}
}
var Son = function(){
act();
}
Son.__proto__ = Father;
Son();
This doesn't work, when Js Engine run Son()
, it should search act()
through it's prototype chain.
But why it only works the following way:
var Father = {
name:'Father',
act:function(){
console.log('the name is '+this.name);
}
}
var Son = {
name:'Son'
}
Son.__proto__=Father;
Son.act();
act is not any property of an object. it is just a variable that points to a function.
When you try to access a property of an object then only Javascript first check if the property exists in that object or not, if it does not then only it search in its prototype until a prototype is null.