Using the prototype feature, you can easily inherit the methods and attributes of the parent class in the subclass .
In the following example, Vegetable is regarded as the parent class and Celery is regarded as the subclass.
Vegetable has the attribute taste, method fun1
Celery has the attribute color, method fun2. If you define another attribute or method with the same name as Vegetable, it will overwrite the corresponding attributes and methods in the parent class Vegetable. method.
function Vegetable(){ this.taste='delicious'; this.fun1 = function(){ alert('Vegetable fun1 doing...'); } } function Celery(){ this.color = 'green'; this.taste = 'bad'; this.fun1 = function(){ alert('Celeryfun1 doing...'); } this.fun2 = function(){ alert('Celery fun2 doing...'); } } Celery.prototype = new Vegetable(); var stick = new Celery(); var polymorphed = stick.taste; alert(polymorphed); alert(stick.color); stick.fun1(); stick.fun2();
The above is the detailed content of Detailed introduction to the method of using prototype to implement OOP inheritance in javascript. For more information, please follow other related articles on the PHP Chinese website!