Home  >  Article  >  Web Front-end  >  Detailed introduction to the method of using prototype to implement OOP inheritance in javascript

Detailed introduction to the method of using prototype to implement OOP inheritance in javascript

黄舟
黄舟Original
2017-03-18 15:04:361245browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn