javascript实现继承的几种主要方法

10次阅读

共计 1435 个字符,预计需要花费 4 分钟才能阅读完成。

//1. 原型链继承
var supClass = function(name, sex) {
this.name = name || ‘red’
this.sex = sex || ‘good’
this.father = ‘father’
this.say = function() {
console.log(this.name)
}
}
supClass.prototype = {
sayHi() {
console.log(this.name + ‘ hi’)
}
}

/*var sonClass = function(name, sex) {
this.name = name
this.sex = sex
}
console.log(sonClass.prototype)
sonClass.prototype = new supClass() // 核心代码
sonClass.prototype.constructor = sonClass// 核心代码

var son1 = new sonClass(‘red’, ‘s’)
son1.say()*/
// 优点: 简单, 容易实现
// 缺点: 多拷贝了一份 supClass 的属性过来, 并且 supClass 的方法每生成一个新的
// sonClass 就要再重新拷贝一份, 造成了不必要的浪费

//2. 构造函数继承
/*var sonClass = function(name, sex, type) {
supClass.call(this)
this.type = type
this.sex = sex
this.name = name
}
var son1 = new sonClass(‘jay’, ‘man’, ‘goodman’)
son1.say()*/
// 优点: 简单, 容易实现, 可以同时继承多个父对象 (三姓家奴)
// 缺点: 只能继承定义在父元素上的属性或方法, 而对于父元素原型对象上的属性或方法
// 则无法继承

//3. 混合继承
/*var sonClass = function(name, sex, type) {
supClass.call(this)
this.type = type
this.sex = sex
this.name = name
}
sonClass.prototype = new supClass()
sonClass.prototype.constructor = sonClass

var son1 = new sonClass(‘jay’, ‘man’, ‘goodman’)
son1.say()
son1.sayHi()*/
// 优点: 几乎完美
// 缺点: 实现复杂, 使用原型继承的部分仍然没有解决会多拷贝一份父类属性从而造成
// 不必要的空间浪费的问题 (可以在 sonClass 的 prototype 中看到被屏蔽的继承自父类的属性)

//4. 寄生组合式继承
// 使用工厂函数将父元素的原型剥离出来单独赋值给子元素的原型
function birth(f, s) {
var prototype = Object(f.prototype)
s.prototype = prototype
s.prototype.constructor = s
}

// 组合式继承

/*var sonClass = function(name, sex, type) {
supClass.call(this)
this.type = type
this.sex = sex
this.name = name
}
birth(supClass, sonClass)

var son1 = new sonClass(‘jay’, ‘man’, ‘goodman’)
son1.say()
son1.sayHi()*/

// 优点: 完美
// 缺点: 实现困难

正文完
 0