小编ChG*_*ChG的帖子

如何使用不同上下文的es6构造函数指令

是否可以通过更改"this"上下文(call,apply或其他)来在另一个实例上使用es6构造函数指令?这可以使用es5"类".这是我的意思的一个小例子:

function ES5() {
  this.foo = 'foo';
}

class ES6 {
  constructor() {
    this.bar = 'bar';
  }
}

var a = new ES6();
ES5.call(a);
console.log(a.foo + a.bar); //foobar



var b = new ES5();
//Reflect.construct(ES6); ??
ES6.call(b); //TypeError: Class constructor ES6 cannot be invoked without 'new'

console.log(b.foo + b.bar); //how to get foobar here too?
Run Code Online (Sandbox Code Playgroud)

编辑: 我的问题与新关键字无关.我正在寻找的答案是如何使用另一个"this"上下文(带或不带new关键字)运行es6构造函数中的指令.

javascript constructor ecmascript-5 ecmascript-6

6
推荐指数
1
解决办法
237
查看次数