Class 的取值函数(getter)和存值函数(setter),写了一段测试代码:
let str = 'nihao';
class MyClass {
constructor() {
}
get prop() {
return str ;
}
set prop(value) {
str = value;
}
}
class ParentClas extends MyClass{
constructor(){
super();
this.prop='haha';
}
}
let parentClass=new ParentClas();
console.log('parentClass.prop',parentClass.prop);
parentClass.prop="heihei";
console.log('parentClass.prop',parentClass.prop);
console.log("str",str);
运行结果为:
按照我的理解,parentClass对象有了自己的prop属性,
parentClass.prop的访问结果是haha,没有问题
但是parentClass.prop="heihei";以后,修改的应该是parentClass对象自身的prop属性,parentClass.prop属性为heihei,也没有问题,但是为什么str变量竟然也是heihei了,按道理,不应该访问到MyClass原型链呀。
这个问题跟ES6的继承机制有关系。
function Father() {
}
function Children(...args){
Father.apply(this, args)
}
Children.prototype = new Father()
ES5的继承,
实质是先创造子类的实例对象this
然后再将父类的私有属性添加到this上面
最后来改变原型链的指向
但也会有一些问题
假设父类构造函数上存在计数
这也会导致计数不准确的问题
ES6的继承机制完全不同
实质是先创造父类的实例对象this
所以必须先调用super方法
(即便子类没有书写constructor也会默认添加)
然后再用子类的构造函数修改this