avatar

目录
JavaScript继承

组合继承:

ES5中常见的继承方式,利用构造函数和prototyoe属性实现

javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Super(){
this.flag = true;
}
Super.prototype.getFlag = function(){
return this.flag;
}
function Sub(){
this.subFlag = false;
Super.call(this);
}
Sub.prototype = new Super(); // Super后面加不加括号,结果一样
Sub.prototype.getSubFlag = function() {
return this.subFlag;
}
var obj = new Sub();
console.log(obj.getSubFlag());

ES6 class继承:

利用ES6的class语法糖实现继承,和ES5中的实现的继承很相似;提供了new.target和super的接口;

javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Super {
constructor() {
this.flag = true;
}
getFlag() {
return this.flag;
}
}
class Sub extends Super {
constructor() {
super();
this.subFlag = false;
}
getSubFlag() {
return this.subFlag;
}
}
var obj = new Sub();
console.log(obj.getSubFlag());

JavaScript继承本质 无类继承:

JavaScript实现的是基于原型的继承方式,不是方法/属性的复制,而是委托,所以称为对象委托感觉更为合适,对象都是属性包;

javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const father = {
flag: true,
getFlag() {
return this.flag;
},
};
const child = {
childFlag: false,
getAllFlag() {
return this.childFlag;
},
};
Object.setPrototypeOf(child, father);
console.log(child.getAllFlag());
文章作者: 盛顺炎
文章链接: https://www.shengshunyan.xyz/2018/10/08/JavaScript%E7%BB%A7%E6%89%BF/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 果实的技术分享
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论