对象继承常见方式
- 经过原型链实现继承
- 经过对象冒充实现继承
- 经过call方式实现继承
- 经过apply方式实现继承
1.经过原型链实现继承以下所示
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
alert('使用原型获得'+this.name);
}
var per = new Person('李端','26');
per.sayHello();
//建立新对象并实现继承
function Student(){};
Student.prototype = new Person('端瑞','23')
var stu = new Student();
stu.sayHello();
2.使用对象冒充实现继承
function Person(name,age){
this.name = name ;
this.age = age;
this.showName = function(){
alert('我是'+name);
}
}
function Child(){
//这三句代码最关键
this.temp = Person;
this.temp('李端','26');
delete this.temp;
}
var child = new Child();
child.showName();//我是李端
3.经过call的方式实现
function Person(name,age){
this.name = name ;
this.age = age;
this.showName = function(){
console.log('我是'+name);
}
}
function Child(){
Person.call(this,'李端','26');
};
var child = new Child();
child.showName();
4.经过apply方式实现
function Person(name,age){
this.name = name ;
this.age = age;
this.showName = function(){
console.log('我是'+name);
}
}
function Child(){
Person.apply(this,['李端','26']);
};
var child = new Child();
child.showName();
// 注意:js中call和apply均可以实现继承,惟一的一点参数不一样,func.call(func1,var1,var2,var3)对应的apply写法为:func.apply(func1,[var1,var2,var3])。