Home > Web Front-end > JS Tutorial > body text

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

黄舟
Release: 2017-03-18 15:04:36
Original
1303 people have browsed it

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template