如何解决“ super”关键字无法访问javascript中的父属性
class Base{
constructor(val){
this.val = val;
}
basep = 'default1';
basef(){
return 2;
}
}
class Test1 extends Base{
constructor(val,name){
super(val);
this.name=name;
}
getp(){
console.log(this.name,this.val);
console.log(this.basep); //(in case of proerty) result: 'default1'. if "this" is changed to "super" ===> result: undefined
console.log(super.basef()); //(in case of methods) this and super both work.
}
}
test= new Test1(1,3);
test.getp();
在Java中,“ this”和“ super”都可以很好地获取父母属性,但是在javascript中似乎只有这才有效。 为什么有区别?
解决方法
在Java中,属性名称放在作用域中,并且如果它们是由不同的类创建的,则可以具有相同名称的两个不同属性。不过,这根本不是在具有原型继承的JavaScript中工作的方式。
在JavaScript中,数据属性(通过赋值创建)由对象本身拥有。父构造函数直接在子实例上创建.basep
属性。 this.hasOwnProperty('basep')
将是true
。
super
关键字用于访问父级.prototype
对象上的属性,而不管当前this
的值是什么,但仍允许在this
上调用它们目的。 basef
方法是Base.prototype
上的属性,而basep
不是。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。