Javascript 为什么TypeScript允许;这";在方法中被省略?
以下类型脚本编译时没有错误:Javascript 为什么TypeScript允许;这";在方法中被省略?,javascript,typescript,Javascript,Typescript,以下类型脚本编译时没有错误: class Something { name: string; constructor() { name = "test"; } } 这段代码编译时没有错误,似乎认为name变量存在。但是,它会生成不会运行的js,因为我省略了这个关键字: /Users/cburtbrown/Documents/code/ts/js/tstest.js:6 console.log(name);
class Something {
name: string;
constructor() {
name = "test";
}
}
这段代码编译时没有错误,似乎认为name变量存在。但是,它会生成不会运行的js,因为我省略了这个
关键字:
/Users/cburtbrown/Documents/code/ts/js/tstest.js:6
console.log(name);
^
ReferenceError: name is not defined
at Something.action (/Users/cburtbrown/Documents/code/ts/js/tstest.js:6:21)
at Object.<anonymous> (/Users/cburtbrown/Documents/code/ts/js/tstest.js:10:25)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:456:32)
at tryModuleLoad (module.js:415:12)
at Function.Module._load (module.js:407:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:159:18)
at node.js:444:3
即使变量拼写正确,也不应该发生此错误吗?因为
就TypeScript而言,您正在尝试为此属性赋值。当然,当您不在浏览器中运行时,这将失败
您可以通过尝试分配一个值来测试这一点
例如:
class Something {
name: string;
constructor() {
status = "test";
}
}
对我有用。JS版本在node 6.0Oh上运行时没有任何错误,所以它特别是
name
。没有考虑这种可能性。谢谢你的快速回答!在节点6.0上编译得很好,这里没有窗口
。@C14L他说它编译得很好,但无法正确运行。如果您没有使用严格模式,那么它将运行,因为您创建了一个隐式全局变量。
class Something {
name: string;
constructor() {
status = "test";
}
}