借用构造函数
function Wheel(style, wheelSize) {
this.style = style
this.wheelSize = wheelSize
}
function Sit(c, siteColor) {
this.c = c
this.siteColor = siteColor
}
function Car(name, style, wheelSize, c, siteColor) {
this.name = name
Wheel.call(this, style, wheelSize)
Sit.call(this, c, siteColor)
}
var car = new Car('BMW', '花里胡哨', 100, '真皮', '红色')
console.log(car)
//Car {name: 'BMW', style: '花里胡哨', wheelSize: 100, c: '真皮', siteColor: '红色'}
共享原型
Father.prototype.name = 'xiaoming'
function Father() {}
function Son() {}
function inherit(T, O) {
T.prototype = O.prototype
}
inherit(Son, Father)
console.log(new Son().name) //xiaoming
//弊端 地址一样,改了Son,Father也变了
Son.prototype.sex = 'male'
var father = new Father()
console.log(father.sex) //male
圣杯模式
Father.prototype.name = 'xiaoming'
function Father() {}
function Son() {}
// function inherit(T, O) {
// function F() {}
// F.prototype = O.prototype
// T.prototype = new F()
// T.prototype.constuctor = T
// T.prototype.uber = O.prototype
// }
var inherit = (function() {
var F = function() {}
return function(T, O) {
F.prototype = O.prototype
T.prototype = new F()
T.prototype.constuctor = T
T.prototype.uber = O.prototype
}
})()
inherit(Son, Father)
console.log(new Son().name) //xiaoming
Son.prototype.sex = 'male'
console.log(new Father().sex) //undefined
ES5写法
function Human(name){
this.name = name
}
Human.prototype.run = function(){
console.log("我叫"+this.name+",我在跑")
return undefined
}
function Man(name){
Human.call(this, name)
this.gender = '男'
}
var f = function(){}
f.prototype = Human.prototype
Man.prototype = new f()
Man.prototype.fight = function(){
console.log('糊你熊脸')
}
ES6写法
class Human{
constructor(name){
this.name = name
}
run(){
console.log("我叫"+this.name+",我在跑")
return undefined
}
}
class Man extends Human{
constructor(name){
super(name)
this.gender = '男'
}
fight(){
console.log('糊你熊脸')
}
}