前端面试题总结二(js原型继承)
今天這篇文章整理了JS原型和繼承的一些知識點,面試的時候 基!本!都!會!問!還不快認真閱讀下文,看看你還有哪些知識點需要掌握吧~
1.原型鏈
基本思想:利用原型讓一個引用類型繼承另外一個引用類型的屬性和方法。
構(gòu)造函數(shù),原型,實例之間的關(guān)系:每個構(gòu)造函數(shù)都有一個原型對象,原型對象包含一個指向構(gòu)造函數(shù)的指針,而實例都包含一個指向原型對象的內(nèi)部指針。
原型鏈實現(xiàn)繼承例子:
function a() {
this.name = '張三';
}
a.prototype.getName = function() {
return this.name;
}
function b() {
this.name = '李四';
}
//繼承了a
b.prototype = new a();
b.prototype.getName = function (){
return this.name;
}
var instance = newb();
console.log(instance.getName());//'李四'
改簡單點
function a() {
this.name = '張三';
}
a.prototype.getName = function() {
return this.name;
}
var instance = new a();
console.log(instance.getName());//'張三'
2.借用構(gòu)造函數(shù)
基本思想:在子類型構(gòu)造函數(shù)的內(nèi)部調(diào)用超類構(gòu)造函數(shù),通過使用call()和apply()方法可以在新創(chuàng)建的對象上執(zhí)行構(gòu)造函數(shù)。
例子:
functiona() {
this.colors = ["red","blue","green"];
}
functionb() {
a.call(this);//繼承了a
}
varinstance1 =newb();
instance1.colors.push("black");
console.log(instance1.colors);//"red","blue","green","black"
varinstance2 =newb();
console.log(instance2.colors);//"red","blue","green"
3.組合繼承
基本思想:將原型鏈和借用構(gòu)造函數(shù)的技術(shù)組合在一塊,從而發(fā)揮兩者之長的一種繼承模式。
function a(name) {
this.name = name;
this.colors = ["red","blue","green"];
}
a.prototype.sayName = function() {
console.log(this.name);
}
function b(name, age) {
a.call(this,name);//繼承屬性
this.age = age;
}
//繼承方法
b.prototype = new a();
b.prototype.constructor = b;//這個是為了讓b的構(gòu)造函數(shù)重新指回這個類本身,否則的話它會變成之前繼承的那個類的構(gòu)造函數(shù),在后面再調(diào)用的時候可能會出現(xiàn)意想不到的情況
b.prototype.sayAge = function() {
console.log(this.age);
}
var instance1 = new b("Hong",18);
instance1.colors.push("black");
console.log(instance1.colors);//"red","blue","green","black"
instance1.sayName();//"Hong"
instance1.sayAge();//18
var instance2 = new b("su",20);
console.log(instance2.colors);//"red","blue","green"
instance2.sayName();//"su"
instance2.sayAge();//20
3.寄生組合繼承
functionbeget(obj){// 生孩子函數(shù) beget:龍beget龍,鳳beget鳳。
varF =function(){};
F.prototype = obj;
returnnewF();
}
functionSuper(){
// 只在此處聲明基本屬性和引用屬性
this.val = 1;
this.arr = [1];
}
// 在此處聲明函數(shù)
Super.prototype.fun1 =function(){};
Super.prototype.fun2 =function(){};
//Super.prototype.fun3...
functionSub(){
Super.call(this);// 核心
// ...
}
varproto = beget(Super.prototype);// 核心
proto.constructor = Sub;// 核心
Sub.prototype = proto;// 核心
varsub =newSub();
alert(sub.val);
alert(sub.arr);
這個方式是最佳方式,但是太麻煩,一般只是課本上用,不多解釋
4寄生式繼承
functionbeget(obj){// 生孩子函數(shù) beget:龍beget龍,鳳beget鳳。
varF =function(){};
F.prototype = obj;
returnnewF();
}
functionSuper(){
this.val = 1;
this.arr = [1];
}
functiongetSubObject(obj){
// 創(chuàng)建新對象
varclone = beget(obj);// 核心
// 增強
clone.attr1 = 1;
clone.attr2 = 2;
//clone.attr3...
returnclone;
}
varsub = getSubObject(newSuper());
alert(sub.val);// 1
alert(sub.arr);// 1
alert(sub.attr1);// 1
想了解ES6中的繼承請關(guān)注下一篇文章
總結(jié)
以上是生活随笔為你收集整理的前端面试题总结二(js原型继承)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式的征途—3.工厂方法(Facto
- 下一篇: install ADT plugin