gpt4 book ai didi

javascript - TypeScript运行时错误 'undefined'

转载 作者:行者123 更新时间:2023-11-28 20:09:54 25 4
gpt4 key购买 nike

我有以下 HTML + TypeScript,它尝试实例化一个名为 Point 的简单类。单击超链接时,每个 try/catch 子句都会出现以下错误:

错误:

  • 无法读取未定义的“Empty”属性。
  • undefined 不是函数。
  • undefined 不是函数。

HTML:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8" />
<title>TypeScript HTML App</title>
<script src="app.js"></script>
<script type="text/javascript">
function Test()
{
try { alert(MyLibrary.Point.Empty.ToString()); }
catch (e) { alert(e.message); }

try { alert(new MyLibrary.Point(10, 20).ToString()); }
catch (e) { alert(e.message); }

try { alert(MyLibrary.Point.FromPoint(new MyLibrary.Point(10, 20)).ToString()); }
catch (e) { alert(e.message); }
}
</script>
</head>
<body>
<a href="javascript:Test();">Click Me</a>
</body>
</html>

typescript :

module MyLibrary
{
export interface IPoint { X: number; Y: number; ToString(): string; }

export class Point implements MyLibrary.IPoint
{
private _X: number = 0;
private _Y: number = 0;

constructor(x: number, y: number)
{
this._X = x;
this._Y = y;
}

public get X(): number { return (this._X); }
public get Y(): number { return (this._Y); }

public ToString(): string
{
return ("{" + this._X.toString() + "," + this._Y.toString() + "}");
}

public static FromPoint(point: MyLibrary.Point): MyLibrary.Point
{
return (new MyLibrary.Point(point.X, point.Y));
}

private static _Empty: MyLibrary.Point = new MyLibrary.Point(0, 0);
public static get Empty(): MyLibrary.Point { return (MyLibrary.Point._Empty); }
}
}

TypeScript 编译良好,并且该项目以 ECMA5 为目标。不确定幕后发生了什么。

更新:如果我从类中删除静态属性,代码就会开始工作。有什么想法吗?静态属性生成的 JavaScript 如下:

Object.defineProperty(Point, "Empty", {
get: function ()
{
return (MyLibrary.Point._Empty);
},
enumerable: true,
configurable: true
});
Point._Empty = new MyLibrary.Point(0, 0);

最佳答案

在模块的静态成员初始化期间,您无法引用模块内类的限定名称——该类尚不能通过该名称使用。更改这两行:

    private static _Empty: MyLibrary.Point = new MyLibrary.Point(0, 0);
public static get Empty(): MyLibrary.Point { return (MyLibrary.Point._Empty); }

至此

    private static _Empty: MyLibrary.Point = new Point(0, 0);
public static get Empty(): MyLibrary.Point { return (Point._Empty); }

如果检查生成的代码,您可以看到属性 MyLibrary.Point 仅在类的静态初始化发生后才设置。这可能被视为编译器错误。

关于javascript - TypeScript运行时错误 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20058081/

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