對象繼承常見方式
- 經過原型鏈實現繼承
- 經過對象冒充實現繼承
- 經過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])。