所以基本上我有一个es6 js类,其中创建构造函数变量然后在类方法中赋值。后来我创建了一个扩展第一个子类的子类,并将我希望使用的所有变量传递给子类构造函数,然后传递给super方法。在这一个变量正确而另一个变量未定义之后,两者都以相同的方式传递和记录。为什么不定义?
class socket {
constructor() {
this.socket = {};
this.base = '/*string*/';
this.mainIndex;
this.dashboard;
this.user_id;
}
socket_start() {
//do stuff here to start websocket
self.socket.onmessage = function ( event ) {
let stream = JSON.parse( event.data );
this.mainIndex = stream.url.mainIndex;
this.dashboard = stream.url.dashboard;
this.user_id = stream.staffInfo.id;
this.base = stream.base;
console.log( this.user_id ); // "1"
console.log( this.base); // "string"
}
}
}
class main extends socket {
constructor( user_id, base, socket, mainIndex, dashboard ) {
super( user_id, base, socket, mainIndex, dashboard );
console.log( this.user_id ); // undefined <--????
console.log( this.base); // "string"
}
答案 0 :(得分:1)
您的父类忽略传递的任何参数。比较以下两个版本:
class A {
constructor() {
this.name;
}
}
class B extends A {
constructor(name) {
super(name)
}
}
> new B("Hunter");
B {}
现在有一个行为正确的例子:
class A {
constructor(name) {
this.name = name;
}
}
class B extends A {
constructor(name) {
super(name)
}
}
> new B("Hunter");
B { name: 'Hunter' }