// superclass 父類
function Person(first, last) {
this.first = first
this.last = last
}
Person.prototype = {
fullName: function() {
console.log(this.first + ',' + this.last)
},
fullNameReversed: function() {
console.log(this.first + this.last)
},
sayHello: function(str) {
alert(str)
},
}
// subclass 子類
function cuteGirl(args) {
Person.apply(this, args)
// 把父類Person的this綁定到當前子類cuteGirl下
}
// subclass extends superclass 子類繼承父類
cuteGirl.prototype = Object.create(Person.prototype)
// 新建了一個對象,參數(shù)Person.prototype是新創(chuàng)建的對象的原型
cuteGirl.prototype.constructor = cuteGirl
// 修正cuteGirl的構(gòu)造器,因為上面改動了cuteGirl.prototype
var xiaohong = new cuteGirl(['xiao', 'hong'])
xiaohong.sayHello('hhh') // 一個彈窗
xiaohong.fullName() // xiao,hong
xiaohong.fullNameReversed() // xiaohong
// superclass
function Person (first, last) {
this.first = first
this.last = last
}
Person.prototype = {
fullName:function() {
console.log(this.first + ',' + this.last)
},
fullNameReversed:function() {
console.log(this.first + this.last)
},
sayHello:function (str) {
alert(str)
},
}
function Girl (sex) {
this.sex = sex
}
Girl.prototype = {
saySex:function () {
console.log(this.sex)
}
}
// subclass
function cuteGirl (args, sex) {
Person.apply(this, args)
Girl.call(this, sex)
}
// subclass extends superclass
// cuteGirl.prototype = Object.create(Person.prototype)
Object.assign(cuteGirl.prototype, Person.prototype, Girl.prototype)
cuteGirl.prototype.constructor = cuteGirl
var xiaohong = new cuteGirl(['xiao','hong'], '妹子')
xiaohong.sayHello('hhh') // 一個彈窗
xiaohong.fullName() // xiao,hong
xiaohong.fullNameReversed() // xiaohong
xiaohong.saySex() // 妹子
Object.assign() 方法用于將所有可枚舉的屬性的值從一個或多個源對象復制到目標對象。它將返回目標對象。
Object.assign(target, ...sources)
兩個參數(shù),第一個為目標對象,后面的為源對象,該方法的返回值是目標對象。
Object.assign(cuteGirl.prototype, Person.prototype, Girl.prototype)
這一句代碼的作用就是把Person和Girl的原型都加到cuteGirl上面去。
還有其實第一種單繼承可以不使用cuteGirl.prototype = Object.create(Person.prototype)
直接用cuteGirl.prototype = Person.prototype)
也可以實現(xiàn)我們想要的效果。