Home >Web Front-end >JS Tutorial >JavaScript implements methods similar to OOP inheritance based on prototype_javascript skills
The example in this article describes how JavaScript implements OOP-like inheritance based on prototype. Share it with everyone for your reference, the details are as follows:
What should be noted here is that public properties (using this. modifier) can be overridden, and private properties (using var modifier) cannot be overridden
Subclasses cannot access the private properties of the parent class, and the methods of the parent class can access the private variables of the parent class normally.
function Vegetable(){ this.taste='delicious'; var a = 'I\'m Vegetable\'a!' this.fun1 = function(){ alert('Vegetable fun1 doing...'); } this.fun3 = function(){ alert(a); } } function Celery(){ var a = 'I\'m Celery\' a'; this.color = 'green'; this.taste = 'bad'; this.fun1a = function(){ alert('Celeryfun1 doing...'); } this.fun2 = function(){ alert('Celery fun2 doing...'); } this.fun4 = function(){ alert(a); } } Celery.prototype = new Vegetable(); var stick = new Celery(); var polymorphed = stick.taste; //alert(polymorphed); //alert(stick.color); //stick.fun1(); //stick.fun2(); //stick.fun3(); stick.fun4();
I hope this article will be helpful to everyone in JavaScript programming.