// 原型繼承
function Parent(name){
this.type = 'Parent'
this.name = name || 'Parent'
this.attr = {
attr1: 1
}
}
Parent.prototype.say = function(){console.log(this.type)}
function Child(){
this.type = 'Child'
}
Child.prototype = new Parent()
var c = new Child()
var c1 = new Child()
// 缺點(diǎn):1、公用父類屬性缎罢,單實(shí)例修改后影響所有子實(shí)例蝶棋;2转晰、子類實(shí)例化時(shí)無(wú)法給父類傳參
c.attr.attr1=2
c1.attr.attr1 // 2
// 構(gòu)造函數(shù)繼承
function Parent(name){
this.type = 'Parent'
this.name = name || 'Parent'
this.attr = {
attr1: 1
}
}
Parent.prototype.say = function(){console.log(this.type)}
function Child(name){
Parent.call(this,name)
this.type = 'Child'
}
var c = new Child()
var c1 = new Child()
// 缺點(diǎn):1、無(wú)法繼承父類原型上的屬性與方法荒给;2唆阿、無(wú)法復(fù)用父類方法
c.say() //Uncaught TypeError: c.say is not a function
// 寄生組合繼承,ES6的 class 語(yǔ)法也是使用的此種方式
function Parent(name){
this.type = 'Parent'
this.name = name || 'Parent'
this.attr = {
attr1: 1
}
}
Parent.prototype.say = function(){console.log(this.type)}
function Child(name){
// 提現(xiàn)構(gòu)造函數(shù)繼承
Parent.call(this, ...agruments)
this.type = 'Child'
}
// 如下提現(xiàn)原型繼承
Child.prototype = Object.create(Parent.prototype) // 原型寄生在新創(chuàng)建的對(duì)象;
Child.prototype.constructor = Child
var c = new Child('c')
var c1 = new Child('c1')
c.say()
// Object.create 過(guò)程
function createFunc(){
function Fn(){}
Fn.prototype = arguments[0]
Fn.prototype.constructor = arguments[0]
var re = new Fn()
if(arguments[0] === null){
re.__proto__ = null
}
Object.defineProperties(re, arguments[1])
return re
}
// new Object() 過(guò)程
- 創(chuàng)建一個(gè)空的簡(jiǎn)單JavaScript對(duì)象(即{});
- 鏈接該對(duì)象(即設(shè)置該對(duì)象的構(gòu)造函數(shù))到另一個(gè)對(duì)象 锹杈;
- 將步驟1新創(chuàng)建的對(duì)象作為this的上下文 ;
- 如果該函數(shù)沒(méi)有返回對(duì)象鳞尔,則返回this嬉橙。
- new會(huì)創(chuàng)建一個(gè)新對(duì)象早直,并且這個(gè)新對(duì)象繼承構(gòu)造函數(shù)的prototype寥假,也就是說(shuō)創(chuàng)建的實(shí)例的proto指向構(gòu)造函數(shù)的prototype
new Object()會(huì)創(chuàng)建一個(gè)實(shí)例,該實(shí)例的proto指向Object的prototype