標籤:實現繼承 sleep 利用 cto 增加 無法 javascrip pre 父類
1.建立對象
1.字面量對象
2.建構函式
3.Object.create
//1.字面量var obj={ name: ‘字面量‘, show: function(){ console.log(this.name) }}//2.建構函式function fun (name) { this.name=name}var obj=new fun(‘obj‘)//3.Object.createvar obj={name: ‘obj‘}var obj=Object.create(obj)
2.JavaScript繼承1.原型鏈繼承
function Parent(name){ this.name=name this.sleep=function(){ console.log(this.name + ‘在睡覺‘) }}Parent.prototype.eat=function(food){ console.log(this.name + ‘正在吃‘ + food)}function Child(){}Child.prototype=new Parent(‘Child‘)Child.prototype.constructor=Childvar child=new Child()
Child.prototype=new Parent(‘Child‘)就是把Parent執行個體賦值給Child.prototype,也就是說new Child().__proto__===new Parent(‘Child‘)。
可以通過Child.prototype在原型對象上增加新的屬性或方法,也可以通過,child.__proto__在原型對象上添加新的方法和屬性。
缺點:
1.原型對象上的屬性和方法是所有執行個體都可訪問的,而且一個執行個體改變了原型上的方法和屬性都會影響到其他執行個體。
2.建立子類執行個體時,無法向父類建構函式傳參。
2.建構函式繼承
function Parent(name){ this.name=name this.sleep=function(){ console.log(this.name + ‘在睡覺‘) }}Parent.prototype.eat=function(food){ console.log(this.name + ‘正在吃‘ + food)}function Child(){ Parent.call(this,‘child‘)}Child.prototype.eyes=function(){console.log(‘eyes‘)}var child=new Child()
建構函式繼承可以通過call或apply方法實現繼承。這種方法不能繼承原型對象中的屬性和方法,只能繼承執行個體屬性和執行個體方法,但是可以向父類傳參。
3.組合繼承
function Parent(name){ this.name=name this.sleep=function(){ console.log(this.name + ‘正在睡覺‘) }}Parent.prototype.eat=function(food){ console.log(this.name + ‘正在吃‘ + food)}function Child(){ Parent.call(this,‘child‘)}Child.prototype.eyes=function(){console.log(‘eyes‘)}Child.prototype=new Parent()Child.prototype.constructor=Child var child=new Child()
組合繼承是比較好的繼承, 他是原型鏈繼承和建構函式繼承的結合, 合理的利用了這兩種組合的特點,既是子類的執行個體,也是父類的執行個體, 但有一個缺點就是調用了兩次建構函式。
4.組合繼承最佳化
function Parent(name){ this.name=name this.sleep=function(){ console.log(this.name + ‘正在睡覺‘) }}Parent.prototype.eat=function(food){ console.log(this.name + ‘正在吃‘ + food)}function Child(){ Parent.call(this,‘child‘)}Child.prototype = Object.create(Parent.prototype)Child.prototype.constructor=Child var child=new Child()
5.寄生組合繼承
function Parent(name){ this.name=name this.sleep=function(){ console.log(this.name + ‘正在睡覺‘) }}Parent.prototype.eat=function(food){ console.log(this.name + ‘正在吃‘ + food)}function Child(){ Parent.call(this,‘child‘)}function f(){}f.prototype=Parent.prototypeChild.prototype=new f()Child.prototype.constructor=Child var child=new Child()
只調用一次父類的建構函式,避免了在子類原型上建立不必要的,多餘的屬性。
JavaScript繼承總結