【发布时间】:2018-07-19 09:14:25
【问题描述】:
我一直在研究 TypeScript 作为 Angular2/5 的要求,我遇到了一些疑问。 几个月前,我还升级了我对 JS ES6 等的知识。 我很确定我没有错,但为了全面了解 TS,我还是会问你。
这是您可以在此处找到的代码:
https://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties
{
class Octopus {
readonly numberOfLegs: number = 8;
constructor(readonly classAttr: string) { ... } // name attribute
}
console.log( (new Octopus('spicylemoned')).classAttr ); // It works
}
在最近的 JS 更新中,有没有办法像在 TS 中那样在 vanilla 的类构造函数中定义属性? (没有通过this 实例隐式分配它)
{
class Test{
constructor({ passedVar : classAttr } ) { ... };
};
console.log( (new Test({ passedVar : 'sweety' })).classAttr );
//it doesnt work
}
【问题讨论】:
-
我认为在 JavaScript 中没有办法做到这一点。你必须在构造函数中使用
this。
标签: javascript class typescript oop ecmascript-6