【问题标题】:this keyword gives null reference error in browser after compiled from typescript从打字稿编译后,此关键字在浏览器中给出空引用错误
【发布时间】:2018-11-30 05:43:23
【问题描述】:

我运行了一个 gulp 任务来将我的 angualr 打字稿代码(boot.ts 和 UtilComponent.ts)转换为 js 代码。当我的 boot.ts 文件使用 gulp 任务编译时,它会生成 utilscript.js 文件及其 .map 文件。但是,当我尝试在 chrome 浏览器中使用带有 index.html 和脚本标记的 utilscript.js 文件时,它会给出错误“无法读取 'sayHelloWorld' of null”。不过,我所有的事件处理程序方法(如 onclick 或 onchange 方法)都可以正常工作。

我的 boot.ts 文件:

import { UtilComponent} from './util-component';

const utilComponent= new UtilComponent();

我的 UtilComponent.ts 内容:

export class UtilComponent {

    msg: string = 'Hello World';

    constructor() {
        this.initializeMessage()
    }

    initializeMessage() {   
        this.sayHelloWorld();
    }

    sayHelloWorld(){
        console.log("sayHelloWorld Method not implemented."+this.name);
    }
}

this.sayHelloWorld() 行给出Cannot read 'sayHelloWorld' of null。

我的gulpfile.js:

         var gulp = require('gulp');
        var ts = require('gulp-typescript');
        var exec = require('child_process').exec;
        var browserify = require("browserify");
        var source = require('vinyl-source-stream');
        var buffer = require('vinyl-buffer');
        var uglify = require('gulp-uglify');
        var sourcemaps = require('gulp-sourcemaps');
        var tsify = require("tsify");

        gulp.task('ng-build', function(cb) {
            console.log('running ng build...');
            exec('ng build', function (err, stdout, stderr) {
                console.log(stdout);
                console.log(stderr);
                cb(err);
                return true;
            });
        });
        gulp.task('utilscript', function() {
            return browserify({
                    basedir: '.',
                    debug: true,
                    entries: 'scripts/boot.ts'
                })
                .plugin(tsify)
                .bundle()
                .pipe(source('utilscript.js'))
                .pipe(buffer())
                .pipe(sourcemaps.init({loadMaps: true}))
                .pipe(uglify())
                .pipe(sourcemaps.write('./'))
                .pipe(gulp.dest('./dist/'));
        });

        gulp.task('default', [ 'utilscript']);

我的package.json:

    {
      "name": "util-chromejs",
      "version": "0.0.0",
      "license": "MIT",
      "scripts": {
        "ng": "ng",
        "start": "ng serve",
        "build": "ng build",
        "test": "ng test",
        "lint": "ng lint",
        "e2e": "ng e2e"
      },
      "private": true,
      "dependencies": {
        "@angular-devkit/core": "^0.6.8",
        "@angular/animations": "^5.0.0",
        "@angular/common": "^5.0.0",
        "@angular/compiler": "^5.0.0",
        "@angular/core": "^5.0.0",
        "@angular/forms": "^5.0.0",
        "@angular/http": "^5.0.0",
        "@angular/platform-browser": "^5.0.0",
        "@angular/platform-browser-dynamic": "^5.0.0",
        "@angular/router": "^5.0.0",
        "core-js": "^2.4.1",
        "rxjs": "^5.5.2",
        "zone.js": "^0.8.14"
      },
      "devDependencies": {
        "@angular/cli": "1.5.2",
        "@angular/compiler-cli": "^5.0.0",
        "@angular/language-service": "^5.0.0",
        "@types/chrome": "0.0.54",
        "@types/jasmine": "~2.5.53",
        "@types/jasminewd2": "~2.0.2",
        "@types/node": "~6.0.60",
        "browserify": "^14.5.0",
        "codelyzer": "~3.2.0",
        "del": "3.0.0",
        "gulp": "^3.9.1",
        "gulp-sourcemaps": "^2.6.1",
        "gulp-typescript": "^3.2.3",
        "gulp-uglify": "^3.0.0",
        "jasmine-core": "~2.6.2",
        "jasmine-spec-reporter": "~4.1.0",
        "karma": "~1.7.0",
        "karma-chrome-launcher": "~2.1.1",
        "karma-cli": "~1.0.1",
        "karma-coverage-istanbul-reporter": "^1.2.1",
        "karma-jasmine": "~1.1.0",
        "karma-jasmine-html-reporter": "^0.2.2",
        "protractor": "^5.3.2",
        "ts-node": "~3.2.0",
        "tsify": "^3.0.3",
        "tslint": "~5.7.0",
        "typescript": "~2.4.2",
        "vinyl-buffer": "^1.0.0",
        "vinyl-source-stream": "^1.1.0"
      }
    }

更新:如果我将 sayHelloWorld 函数移出类并使其低于然后它可以工作。

 export function sayHelloWorld{

 }

【问题讨论】:

  • 请在您创建UtilComponent 对象实例的位置发布代码。我怀疑您的 this 变量不是它的预期值(例如,您是否在事件处理程序中?)。当直接从 JavaScript 调用 TypeScript 代码而不调用 bind 来正确设置 this 时,经常会发生这种情况。
  • @戴你是对的。它在一个事件处理程序中。抱歉,我的代码没有提到这一点。

标签: javascript node.js angular typescript gulp


【解决方案1】:

您需要使用箭头函数正确设置this 上下文。另见this in TypeScript

export class UtilComponent {
    msg: string = 'Hello World';

    constructor() {
         this.initializeMessage()
    }

    initializeMessage = () => {   
         this.sayHelloWorld(); // without arrow function, the context will be initializeMessage function and thus throwing the error.
    }

    sayHelloWorld = () => {
       console.log("sayHelloWorld Method not implemented."+this.name);
    }
}

【讨论】:

  • 我不喜欢initializeMessage = () => { ,因为这意味着initializeMessage 不再是一种方法,而是一种函数属性(具有隐含的可变性)。虽然这两者在实践中表现相同,但它并不适合我。
  • 另一种方法是将函数绑定到构造函数中的this 上下文。 constructor() { this.initializeMessage = this.initializeMessage.bind(this); this.initializeMessage(); }.
猜你喜欢
  • 2016-08-14
  • 2023-02-08
  • 2020-01-30
  • 1970-01-01
  • 2021-12-29
  • 2018-02-18
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
相关资源
最近更新 更多