[英]Exported typescript class function logs “this” as undefined
我目前有一個可在構造函數中設置類值的Typescript類。 然后,我在類方法中使用“ this”引用這些值。 .ts文件可以正常編譯而不會發出警告。 但是,當我在另一個項目中導入已編譯的.js文件時,如果調用類方法,則會收到一個錯誤消息,即未定義。
我用打字稿為文件寫了一些測試,它們都工作正常。
這是一個簡化的示例。
# class .ts file
export class MyClass {
public myValue: number;
constructor(val: number) {
this.myValue = val;
}
logValue() {
console.log(this);
console.log(this.myValue);
}
}
# regular js project importing built .js file
import { MyClass } from 'myProject'
const x = new MyClass(5);
x.logValue(); // error, cannot read property myValue of undefined, first console.log logs 'undefined';
這是我的tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
// useTypeInferenceAsMuchAsPossible
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"outDir": "./lib",
"allowJs": true,
"target": "es5",
"lib": [
"es7",
"es2015.symbol",
"es2015.symbol.wellknown"
]
},
"include": [
"./src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
謝謝!
這段代碼實際上沒有錯誤 :
const x = new MyClass(5);
x.logValue();
但是,這將出錯:
const x = new MyClass(5);
const logValue = x.logValue;
logValue(); // Error
這是簡單,因為怎么this
工作。
您可以使用箭頭功能 。 更改:
logValue() {
console.log(this);
console.log(this.myValue);
}
至 :
logValue = () => {
console.log(this);
console.log(this.myValue);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.