JavaScript uses Prototype to implement the object-oriented method. javascriptprototype
This example describes how JavaScript uses Prototype to implement object-oriented methods. Share it with you for your reference. The specific analysis is as follows:
Prototype is an attribute of a Function object. It points to another object. All attributes and methods of this object will be inherited by the constructor instance.
At the same time, prototype has a constructor reference pointing to the constructor. In this way, a prototype chain structure of circular reference is successfully formed.
We can directly define the unchanged attributes and methods on the prototype object to save memory overhead.
Function Cat (name, color) {this. name = name; this. color = color;} Cat. prototype. type = 'mammal'; Cat. prototype. eat = function () {console. log ('eat fish ') ;}; var cat1 = new Cat ('Kitty', 'white'); var cat2 = new Cat ('smokey', 'black '); console. log (cat1.type); // mammalconsole. log (cat1.eta === cat2.eta); // TRUE, same referenceconsole. log (cat1.constructor === Cat) // TRUE, from Person. prototype
I hope this article will help you design javascript programs.