Home >Web Front-end >JS Tutorial >JavaScript uses prototype to complete single inheritance_javascript skills

JavaScript uses prototype to complete single inheritance_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:24:52967browse

1. Use prototype to complete single inheritance.

Copy code The code is as follows:

//Define a class A
function A(){
}
//Dynamically call the attribute color for class A, and the method sayColor
A.prototype.color = "blue";
A.prototype.sayColor = function(){
alert(this.color);
};
//Created a class B
function B(){
}
//Let B inherit from A
B.prototype=new A(); //new the object of A and assign it to the prototype of B. B contains all the properties and methods defined in A.
//Can the inherited sayColor be overridden?
B.prototype.sayColor=function(){
alert("Rewrite");
}
var b=new B();
b.color='red';
b.sayColor();
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