What is the problem of js constructor inheritance?

The output of

myfn.b (); / / 0 is a little confusing.

function fn() {
    this.a = 0;
    this.b = function() {
        alert(this.a)
    }
}
fn.prototype = {
    b: function() {
        this.a = 20;
        alert(this.a);
    },
    c: function() {
        this.a = 30;
        alert(this.a);
    }
}
var myfn = new fn();
myfn.b();//0
myfn.c();//30
Mar.11,2021

this is because the instance first calls the instance method, and the b method on the prototype chain is not called.


the statement upstairs is correct. The JavaScript inheritance mechanism is such that if the instance object has a property or method of its own, it will no longer go to the prototype object to look for that property or method. To learn javascript, you can spend some time learning the following teacher Ruan Yifeng's blog, which is accurate and clear. For example, you can see the answer to your question in this article:
prototype object

Menu