我在 TypeScript 中有一个非常简单的用例: 一个类,带有构造函数和实例方法。
我想从构造函数调用此实例方法,但使用“this”解析不正确。
拥有具有实例方法的类并从构造函数调用它们的正确方法是什么?
我有一个 UMD 模块(在我的 tsconfig 中定义为要编译的模块类型)。
我有以下代码:
export namespace TestNS {
export class TestClass {
// Fields
testValue: string;
constructor(val: string) {
this.testValue = val;
this.privateMethod();
}
private privateMethod() {
console.log("private instance method");
}
}//TestClass class
}
它编译为:
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TestNS;
(function (TestNS) {
var TestClass = /** @class */ (function () {
function TestClass(val) {
this.testValue = val;
this.privateMethod();
}
TestClass.prototype.privateMethod = function () {
console.log("private instance method");
};
return TestClass;
}()); //TestClass class
TestNS.TestClass = TestClass;
})(TestNS = exports.TestNS || (exports.TestNS = {}));
});
//# sourceMappingURL=Test.js.map
我用以下方式调用它:
var ex = new TestNS.TestClass("test");
调用时,出现找不到 privateMethod 的错误。
在浏览器中调试原始 js 代码时,类构造函数中的 this
似乎引用“TestNS”命名空间对象,而不是我期望的 TestClass 实例。为什么会这样呢?如果我无法命名空间并使用类实例成员,这似乎是一个明显的问题。
我在这里做错了什么? (我想强制执行这种命名空间来组织对象,以便稍后进行更大的项目)
编辑:为了阐明如何加载此代码,我将提供这些详细信息。
tsconfig.json
{
"compilerOptions": {
"baseUrl": "./js",
"target": "es5",
"sourceMap": true,
"typeRoots" : ["./js/lib/@types"],
"module": "UMD"
},
"exclude": [
"node_modules"
]
}
index.html
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="require.js"></script>
<!-- Data main attribute avoided due to some environment constraints (ie: a CMS) -->
<script src="main.js"></script>
</head>
<body>
<p>Example Text</p>
</body>
</html>
main.js
requirejs.config({
baseUrl: "js",
map: {
'*': {
'Test': 'modules/Test',
}
}
});
requirejs(["Test"],function(TestNS) {
var t = new TestNS.TestClass("value");
}
最佳答案
重要的一点恰好是您尚未添加到问题中的部分......如何加载该代码。
var ex = new TestNS.TestClass("test");
如果您以前的代码未加载,则将出现错误,无论是通过在依赖代码之前添加脚本标记还是通过导入模块...
import { TestNS } from './test.js'
我想这就是缺失的部分。
关于javascript - 在类构造函数内使用 'this' 作为实例方法的 typescript 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53893800/