I know the concept of inheritance in JavaScript is through prototype chain, but I'm not sure I understand it right. When a property is been read, the engine will first search for the instance's own property, if not found will search for the [[Prototype]] property of the instance, which is a reference to the prototype of the function that creates the instance, the search will go on until it reaches to the Object.prototype. For the following code:
var person1 = {
name: "Qiushi",
sayName: function() {
console.log(this.name);
}
};
person1.sayName(); // Qiushi
var person2 = Object.create(person1);
person2.name = "Alex";
console.log(person2.hasOwnProperty("sayName")); // false
person2.sayName(); // Alex
when person2 is inherit from person1, so that person2 can use the method defined in person1. But the sayName method is not a property of the prototype of person1, but instead it is just a own property of it. My question is as the method searching is following alone the prototype chain, how would person2 use a method which is not in this chain?
-------------------------------FINAL EDIT-------------------------
If you have same concern for the problem, please read the conversation between me and Jimbo.
person2prototype). That's why we havehasOwnProperty()in the first place.hasOwnProperty()is true for that particular object), or one of its parents in the chain has (thenhasOwnProperty()is true for that particular parent, but false for the initial object), or none has, then the property is undefined.