常见的对象继承方式

对象继承常见方式

  • 通过原型链实现继承
  • 通过对象冒充实现继承
  • 通过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])。

posted @ 2017-03-30 22:06  追梦-dream  阅读(293)  评论(0)    收藏  举报