gpt4 book ai didi

javascript - 如何使用 AMD 模块从纯 js 中创建 TypeScript 类的对象实例

转载 作者:行者123 更新时间:2023-11-28 13:32:40 26 4
gpt4 key购买 nike

假设我有以下文件tests.ts:

module tests {

export class Greeter
{
sayHello() {
console.log("hello world");
}
}
}

并将其编译为 AMD 模块。究竟如何在常规 JavaScript(不是 typescript !)文件中创建 Greeter 的对象实例?

我在想这样的事情:

require(['tests', function(tests) {
var greeter = new tests.Greeter();
greeter.sayHello();
}

但这似乎不起作用 - 调试器向我显示测试是 __proto__ 但我在其中找不到成员“Greeter”。

最佳答案

您忘记了顶级模块上的export关键字,因此顶级代码块实际上不会导出任何可见的外部模块。

另外,请参阅Modules in TypeScript “不必要的命名空间”陷阱:

If you're converting a program from internal modules to external modules, it can be easy to end up with a file that looks like this:

shapes.ts

 export module Shapes {
export class Triangle { /* ... */ }
export class Square { /* ... */ } }
}

The top-level module here Shapes wraps up Triangle and Square for no reason. This is confusing and annoying for consumers of your module:

shapeConsumer.ts

 import shapes = require('./shapes'); var t = new
shapes.Shapes.Triangle(); // shapes.Shapes?

A key feature of external modules in TypeScript is that two different external modules will never contribute names to the same scope. Because the consumer of an external module decides what name to assign it, there's no need to proactively wrap up the exported symbols in a namespace.

To reiterate why you shouldn't try to namespace your external module contents, the general idea of namespacing is to provide logical grouping of constructs and to prevent name collisions. Because the external module file itself is already a logical grouping, and its top-level name is defined by the code that imports it, it's unnecessary to use an additional module layer for exported objects.

关于javascript - 如何使用 AMD 模块从纯 js 中创建 TypeScript 类的对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23685844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com