In traditional JavaScript, there is a disguised concept of inheritance, it is through the use of prototyping techniques to achieve. In ES5, ES6 seen using the new syntax just syntactic sugar underlying prototype of OOP. Create a class is to use the JavaScript function in the completion.
var animalGroups = { MAMMAL: 1, REPTILE: 2, AMPHIBIAN: 3, INVERTEBRATE: 4 }; function Animal(name, type) { this.name = name; this.type = type; } var dog = new Animal("dog", animalGroups.MAMMAL); var crocodile = new Animal("crocodile", animalGroups.REPTILE);
Here we create objects (using the new keyword) as a class, can be used as an additional way to class method:
Animal.prototype.shout = function() { console.log(this.name+'is'+this.sound+'ing...'); }
Here you may be in doubt. Class did not sound properties. Yes, it is intended that the subclass inherits the transfer of the above categories. JavaScript, inheritance follows:
function Dog(name, type) { Animal.call(this, name, type); this.sound = 'bow'; }
I define a more specific function, called the Dog. Here, in order to inherit the Animal class, I need to pass this and other call parameters. Used to instantiate a manner 德国牧羊犬
.
var PET = Dog ( "German Shepherd" , animalGroups.MAMMAL); the console.log (PET); // Returns Dog {name: "German Shepherd", type: 1, sound: "bow"}
We are not allocated in the sub-functions name
and type
properties, we call a super-function Animal and set the appropriate properties. pet parent class having attributes (name, type). But the way to do that. ? They also inherited a look at it:
pet.shout(); // Throws error
Why is this so? The reason why this occurs is because no let JavaScript to inherit the parent class method. How to solve?
// Link prototype chains Dog.prototype = Object.create(Animal.prototype); var pet = new Dog("germanShepard", animalGroups.MAMMAL); // Now shout method is available pet.shout(); // 德国牧羊犬 bowing...
You can now use the shout
method. We can use the JavaScript function to check object.constructor given object's class pet is to look at what categories:
pet.constructor; // returns Animal
This is vague, Animal is a parent. But in the end is what type of pet it? Pet should be Dog
of type. The reason is the Animal type, because the constructor Dog class:
Dog.prototype.constructor; // returns Animal
It is of type Animal. We should set it to Dog itself, all instances of this class (objects) to give the correct class name.
Dog.prototype.constructor = Dog;
About prototypal inheritance, we should remember here the following:
-
Class attributes using
this
bind -
Class method uses
prototype
the object to bind -
In order to inherit property, use the
call
function to passthis
-
For inherited methods, using the prototype parent and child connection Object.create
-
Always subclass constructor set itself the object to obtain its correct type