The problem of using a prototype circuit

If I have a constructor that takes several arguments:

var Mammal = function(name, weight) {
    this.name = name;
    this.weight = weight;
}


Mammal.prototype.makeSound = function(sound) {
    alert(sound);
} 

Mammal.prototype.getName = function() {
    return this.name;
}

and I want to do some inheritance:

var Human = function(name,weight,language,location) {
    //code         
}

Human.prototype = new Mammal();

On the last line there is no Human prototype that is assigned undefined for name and weight parameters? I see this code all the time ... I know that the Human constructor is fed the name and weight parameters, but it seems useless that the prototype gets these values ​​undefined. I know this only works because javascript is strong enough for you to do this. Is there any way around this?

+3
source share
2 answers

What worries you?

Human.prototype = new Mammal();
alert( Human.prototype.name ); // undefined
alert( Human.prototype.foo );  // undefined

You may consider them different. The reason you are not writing:

Human.prototype = Mammal.prototype;

Mammal , .

var Mammal = function(name, weight) {
    this.name = name;
    this.weight = weight;
    this.somefun = function() {
      // this can't be inhereted by
      // Mammal.prototype
    }
}

, Constructor Chaining:

var Human = function(name,weight,language,location) {
    this.language = language;
    this.location = location;
    // call parent constructor
    Mammal.apply(this, arguments);       
}

, ? name weight, Human Human.

+2

, - :

var Human = function(name,weight,language,location) {
    Mammal.call(this, name, weight);//calls the parent constructor        
    this.language = language;
    this.lcoaiton = location;
}

Human.prototype = new Mammal();
+1

Source: https://habr.com/ru/post/1772440/


All Articles