如何使用类型脚本创建自动执行的匿名函数?
例如
(function() {
var someClass = {
}
}.call(this));
我想要一个可以用于Node.js的内置插件,也适用于fron-tend。
答案 0 :(得分:22)
/**
* Self executing anonymous function using TS.
*/
(()=> {
// Whatever is here will be executed as soon as the script is loaded.
console.log('executed')
})();
我想要一个可以用于Node.js的内置插件,也适用于fron-tend。
在这种情况下,您应该在AMD中编译TypeScript并在前端使用AMD加载程序,如http://requirejs.org/docs/start.html
在服务器端,您还需要使用requirejs
节点包来加载文件。看看这个:http://requirejs.org/docs/node.html
基本上有两种方法可以将TS编译为JS,使用符合浏览器标准的AMD,或者使用符合node.js的CommonJS。在浏览器或服务器中加载AMD脚本需要使用兼容AMD的加载器,而* requirejs **就是其中之一。 (最着名/最常用的我说的)
答案 1 :(得分:3)
TypeScript中的第一条规则:任何有效的JavaScript都是有效的TypeScript。
不,目前在TS中编写自执行匿名函数没有特殊方法。
但是,下面是一些可能在您的情况下有用的代码。
TS中的每个类都被编译为(命名的)自执行匿名函数,它返回一个函数。
示例:
//ts
class someClass {
someProperty = "this is a property";
}
转换为
//js
var someClass = (function () {
function someClass() {
this.someProperty = "this is a property";
}
return someClass;
})();
希望这有一些帮助。
答案 2 :(得分:0)
Typescript中的自执行,立即,递归的顶级React函数:
(function handleAutomatonTypeChange(newtype: AutomatonType) {
ReactDOM.render(
<Automaton automatonType={newtype}
onAutomatonTypeChange={handleAutomatonTypeChange} />,
document.getElementById('automaton')
);
})('diadic');
答案 3 :(得分:-2)
(function(){
document.body.innerHTML = "Self Calling Function";
}.call(this));