Search code examples
javascriptangulartypescriptprototype

Javascript prototype function calling from typescript


I have an Angular app having multiple external JavaScript files included from /app/asset/scripts and working fine while calling from <script> tag. I am trying to call JavaScript function from angular(.ts), but it throws an error. Here is the snippet:

src/app/asser/scripts/viewer.js

function MyView(x, y) {
  //other stuffs
  this.initView(x, y); <---- error here
}

MyView.prototype.initView = function(x, y) {
  console.log("initView");
}

src/app/viewer/viewer-component.ts

declare var MyView: any;

export class myComponent{
  constructor(){}
  init(){
    this.view = MyView(1000, 800);
  }
}

While invoking the initView from JS. It throws the error below:

ERROR TypeError: this.initView is not a function
    at MyView (view.js:69)
    at RendererService.push.i2er.RendererService.SetupURL (viewer0.ts:31)

How this error can be resolved?

Thanks


Solution

  • function MyView(x, y) {
      //other stuffs
      this.initView(x, y); <---- error here
    }
    
    MyView.prototype.initView = function(x, y) {
      console.log("initView");
    }
    

    MyView is a constructor function.

    In order to use this you should call it with new keyword

    new MyView(2,2)
    

    I'm not sure that you need declare var MyView: any;