目前在ES5中,我们很多人在框架中使用以下模式来创建类和类变量,这很舒服:
// ES 5
FrameWork.Class({
variable: 'string',
variable2: true,
init: function(){
},
addItem: function(){
}
});
Run Code Online (Sandbox Code Playgroud)
在ES6中,您可以本机创建类,但没有选项可以使用类变量:
// ES6
class MyClass {
const MY_CONST = 'string'; // <-- this is not possible in ES6
constructor(){
this.MY_CONST;
}
}
Run Code Online (Sandbox Code Playgroud)
遗憾的是,上面的代码不起作用,因为类只能包含方法.
我知道我可以this.myVar = true在constructor...但我不想"垃圾"我的构造,特别是当我有一个更大的类20-30 +参数.
我正在考虑处理这个问题的许多方法,但还没有找到任何好的方法.(例如:创建一个ClassConfig处理程序,并传递一个parameter与该类分开声明的对象.然后处理程序将附加到该类.我正在考虑WeakMaps以某种方式集成.)
你有什么样的想法来处理这种情况?
在TypeScript中,const关键字不能用于声明类属性.这样做会导致编译器出错,"类成员不能拥有'const'关键字."
我发现自己需要在代码中清楚地指出不应该更改属性.如果我在声明属性后尝试为该属性分配新值,我希望IDE或编译器出错.你们是如何实现这一目标的?
我目前正在使用只读属性,但我是Typescript(和JavaScript)的新手,并想知道是否有更好的方法:
get MY_CONSTANT():number {return 10};
Run Code Online (Sandbox Code Playgroud)
我正在使用typescript 1.8.建议?
PS:我现在正在使用打字稿2.0.3,所以我接受了大卫的回答
有谁可以帮助我吗
我有2个文件main.ts和hi.ts
hi.ts:
export const hello = "dd";
Run Code Online (Sandbox Code Playgroud)
main.ts:
import { hello } from "./hi";
...
class A {
public sayHello() {
console.log("hello=" + hello);
}
...
}
Run Code Online (Sandbox Code Playgroud)
我有例外:
未捕获的ReferenceError:未定义hello(...)
如何从A类中看到这个const变量?可能吗?
有没有办法const在类的构造函数中定义一个?
我试过这个:
class Foo {
constructor () {
const bar = 42;
}
getBar = () => {
return this.bar;
}
}
Run Code Online (Sandbox Code Playgroud)
但
var a = new Foo();
console.log ( a.getBar() );
Run Code Online (Sandbox Code Playgroud)
返回undefined.
假设我有两个这样的ES6类:
class Base {
static something() {
console.log(this);
}
}
class Derived extends Base {
}
Run Code Online (Sandbox Code Playgroud)
然后我打个电话:
Derived.something();
Run Code Online (Sandbox Code Playgroud)
请注意,我正在通过子类调用超类上定义的静态方法.
这并没有给我的错误.它打印
[Function: Derived]
Run Code Online (Sandbox Code Playgroud)
因此,this在静态方法中访问似乎在这里工作.
我需要一个超级类的所有子类的公共静态方法,我需要能够知道什么子类正在调用此方法.
现在我的问题是this在静态方法中使用是否合法.我知道这些静态方法成为类方法,因此this自然会指向它们被调用的类对象.(类对象是构造函数.)
但我似乎无法找到任何明确的资源,表明ES规范允许这样做.
这看起来像一个很好的介绍ES6类,但没有谈及this与static.
javascript static-methods this-pointer ecmascript-6 es6-class
我有一个遵循 ECMA6 标准的 JavaScript 类,我想在其中创建一个静态变量。
为此,我阅读了以下文档:
第一个链接演示了如何在 ECMA 6 中的类中创建静态方法,而第二个链接演示如何使用原型和函数来实现在 ECMA6 之前创建静态变量。
这些都不是我想要的。我正在寻找这样的东西:
class AutoMobile {
constructor(name, license) {
//class variables (public)
this.name = name;
this.license = license;
}
//static variable declaration
static DEFAULT_CAR_NAME = "Bananas-Benz";
}
Run Code Online (Sandbox Code Playgroud)
但是,前面的示例不起作用,因为static关键字仅用于方法。
如何使用 ECMA6 在 JavaScript 的类中创建静态变量?
我理解thisjavascript中的关键字.我已经用它喜欢this.method()或this.variable =.但这是什么().请参阅以下代码:
static fromTX(tx, index) {
return new this().fromTX(tx, index);
}
Run Code Online (Sandbox Code Playgroud)
请帮助我理解在javascript和上面的代码示例中使用this().
javascript ×5
ecmascript-6 ×4
typescript ×2
class ×1
const ×1
es6-class ×1
export ×1
import ×1
this ×1
this-pointer ×1