今天開通了頭條號,作為一個前端工程師,我會把在工作中遇到的技術知識總一個總結 ,並及時分享給小夥伴們,希望小夥伴們可以喜歡。李某再次謝過(^.^)
對象繼承常見方式
1. 通過原型鏈實現繼承
2.通過對象冒充實現繼承
3.通過call方式實現繼承
4. 通過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])。