在js中并没有类似于java中的extends关键字去继承其他的一个类。我们可以通过以下的方式去实现js中的继承特性。
方法一:对象冒充
function Parent(username) {
this.username = username;
this.hello=function() {
alert(this.username);
}
}
function Child(username,password) {
this.method = Parent;
this.method(username); //这句话是关键
delete this.method;
this.password = password;
this.world=function(){
alert(this.password);
}
}
var parent = new Parent("lgk");
parent.hello(); //lgk
var child = new Child("ahau","aaa");
child.hello(); //ahau
child.world(); //aaa
方法二:function的call()方法
function Parent(username) {
this.username = username;
this.hello=function() {
alert(this.username);
}
}
function Child(username,password) {
Parent.call(this, username);
this.password = password;
this.world=function(){
alert(this.password);
}
}
var parent = new Parent("lgk");
parent.hello(); //lgk
var child = new Child("ahau","aaa");
child.hello(); //ahau
child.world(); //aaa
call是每个function中都有的方法,call中的第一个参数表示将谁传递给调用了call方法的函数(在这里也就是将Child传递给Parent),从第二个开始后面的参数都是以此对应传递给Parent中的参数
方法三:function的apply()方法
function Parent(username) {
this.username = username;
this.hello=function() {
alert(this.username);
}
}
function Child(username,password) {
Parent.apply(this, new Array(username));
this.password = password;
this.world=function(){
alert(this.password);
}
}
var parent = new Parent("lgk");
parent.hello(); //lgk
var child = new Child("ahau","aaa");
child.hello(); //ahau
child.world(); //aaa
apply中的第一个参数和call中的一样,apply中只有2个参数,第二个参数是一个数组,数组中的元素依次对应Parent中的参数。
方法四:原型链方式。
function Parent() {
}
Parent.prototype.username = "lgk";
Parent.prototype.sayHello=function(){
alert(this.username);
}
function Child() {
}
Child.prototype = new Parent();//这句话是最关键的,它将Parent上的所有属性和方法都附加在了Child.prototype上
Child.prototype.password = "ahau";
Child.prototype.sayWorld=function(){
alert(this.password);
}
var child = new Child("ahau","aaa");
child.sayHello(); //lgk
child.sayWorld(); //ahau
方法五:混合方式(属性用构造方法的方式,方法用原型的方式)
function Parent(hello){
this.hello = hello;
}
Parent.prototype.sayHello=function() {
alert(this.hello);
}
function Child(hello,world){
Parent.call(this, hello);
this.world = world;
}
Child.prototype = new Parent();
Child.prototype.sayWorld=function() {
alert(this.world);
}
var child = new Child("ahau","aaa");
child.sayHello(); //ahau
child.sayWorld(); //aaa
JS继承五种方式
本文介绍了JavaScript中实现继承的五种方法,包括对象冒充、Function的call/apply方法、原型链方式及混合方式等,并提供了详细的代码示例。
932

被折叠的 条评论
为什么被折叠?



