isPrototypeOf in Javascript

前端 未结 3 1159
星月不相逢
星月不相逢 2021-02-20 11:02

I am a beginner to JavaScript and on my way to Prototypes in JavaScript.
As per the article here

Creating

3条回答
  •  无人共我
    2021-02-20 11:14

    I agree with you - the sentence "The constructor function is the prototype for your person objects" is confusing and inaccurate. Instead, your understanding is correct although let me elaborate more.

    Basically, whenever you create a function in JavaScript, it will automatically have a property on it called .prototype and the value associated with it will be an object. In your case, the person function also has this .prototype property. When you create new instances of person, each instance will be set up as inheriting from the object associated with the person function's .prototype property - the instance's prototype. This inheritance means that property look-ups are delegated to this prototype object. The key here is that when your person instances look up a property, they will first look up the property on themselves, and if the property isn't found, they will go up the prototype chain.

    Looking at your example, here is what is correct:

    person.prototype.isPrototypeOf( new person() );
    

    In other words, any instance of person knows to delegate to the object associated with person.prototype whenever the instance can't find a property on itself.

提交回复
热议问题