Mik*_*aAK 17 javascript constructor ecmascript-6
最近我一直在用ES6测试类,我注意到在创建类时你不能指定构造函数给出的值.
以前在ES5中这是可能的.
在这两种情况下,我都会实例化类new MyClass
.我想这样做是因为我可以返回当前类的子集,只有函数.
My class was init with: Blahvar MyClass = function() {
this.initVar = 'Blah'
return 'My Class was init with: ' + this.initVar
}
Run Code Online (Sandbox Code Playgroud)
{}class Bob {
constructor() {
return 'hello'
}
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*obG 28
根据TC39网站上的Class文章,ES6类语法有一个隐式构造函数,如果类定义中没有提供这样的函数,则会调用该函数.
这可以通过提供您自己的构造函数并返回您想要的任何对象来覆盖,例如:
class Bob {
constructor(name) {
return {hi: name}; // returns an object other than *this*.
}
}
Run Code Online (Sandbox Code Playgroud)
在行动:
var bob = new Bob('bob');
console.log(bob.hi); // 'bob'
Run Code Online (Sandbox Code Playgroud)
要扩展课程,您可以:
class Bill extends Bob {
}
Run Code Online (Sandbox Code Playgroud)
但是,extends也有一个隐式构造函数,因此它将返回一个继承自Bob.prototype的Bill的新实例.由于hi是在构造函数中定义的而不是继承的,因此您得到:
var bill = new Bill('bill');
console.log(bill.hi); // undefined
Run Code Online (Sandbox Code Playgroud)
要像Bob一样初始化Bill ,请提供一个调用super的构造函数.此调用还将Bill的此对象更改为super返回的值,例如
class Bill extends Bob {
constructor(name) {
super(name);
}
}
Run Code Online (Sandbox Code Playgroud)
现在:
var bill = new Bill('bill');
console.log(bill.hi); // bill
Run Code Online (Sandbox Code Playgroud)
另外值得注意的是,classDeclaration的主体始终是严格的模式代码.
作为一个可运行的片段:
class Bob {
constructor(name) {
return {hi: name}; // returns an object other than *this*.
}
}
var bob = new Bob('bob');
console.log(bob.hi); // 'bob'
class Bill extends Bob {
constructor(name) {
super(name);
}
}
var bill = new Bill('bill');
console.log(bill.hi); // billRun Code Online (Sandbox Code Playgroud)