继承是什么?
现实生活中,继承是泛指把前人的作风、文化、知识等接受过来
那在 JavaScript 中,简单来说,就是一个对象拥有另一个对象的属性和方法。
为什么要用继承?
ES5 继承的实现(基于原型链)
// 创建一个 Human 构造函数
function Human(name) {
this.name = name
}
Human.prototype.run = function () {
console.log('I can run')
}
// 创建一个 Man 构造函数
function Man(name) {
Human.call(this, name)
this.gender = '男'
}
Man.prototype.fight = function () {
console.log('I can fight')
}
// 让 Man 的原型对象的 proto 指向 Human 的原型对象
Man.prototype.__proto__ = Human.prototype
// 来 new 一个 Man 实例:
var Tony = new Man('Tony')
console.log(Tony)
本来 Man.prototype.__ proto__ 是指向 Object.prototype 的,
但是我们加了一句 Man.prototype.__ proto__ = Human.prototype ,
所以现在 Man.prototype.__ proto__ 就指向了 Human.prototype 。
ES6 实现继承(class 和 extends):
class Human {
constructor(name) {
this.name = name
}
run() {
console.log('I can run')
}
}
class Man extends Human {
constructor(name) {
super(name)
this.gender = '男'
}
fight(){
console.log('I can fight')
}
}
\\ 同样,再来 new 一个 Man 实例看看:
var Allen = new Man('Allen')
console.log(Allen)
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!