简体   繁体   English

在javascript中使用打字稿值

[英]use typescript value in javascript

hi i need to create a simple calcuator in angular with javascript . 嗨,我需要用javascript创建一个简单的计算器。

now i use this code in javascript : 现在我在javascript中使用此代码:

$(document).ready(function () {
  switch (this.operator) {
    case '+':
      this.ResultAns += this.first + this.second;
      break;
    case '-':
      this.ResultAns += this.first - this.second;
      break;
    case '*':
      this.ResultAns += this.first * this.second;
      break;
    case '/':
      this.ResultAns += this.first / this.second;
      break;
  }

and i defined this variable n type script: 我定义了此变量n类型脚本:

  first: string = "";
  second: string = "";
  operator: string = "";
  ResultAns: number;

now when i need to use this variable it show undefined . 现在,当我需要使用此变量时,它显示为undefined

how can i use this variable in javascript ??????? 我如何在javascript中使用此变量?

this in JavaScript has different scopes. this在JavaScript中有不同的范围。 You could read a blog post, I googled one for you . 您可以阅读一篇博客文章, 我为您搜索了一篇博客文章。
When you use a function keyword, this will refer to the caller (in your case, to document ). 当您使用function的关键字, this将涉及到调用者(在你的情况,以document )。

You can use an arrow function : 您可以使用箭头功能

$(document).ready(() => {
  switch (this.operator) {
    case '+':
      this.ResultAns += this.first + this.second;
      break;
    case '-':
      this.ResultAns += this.first - this.second;
      break;
    case '*':
      this.ResultAns += this.first * this.second;
      break;
    case '/':
      this.ResultAns += this.first / this.second;
      break;
  }

Anyway, in Angular, you shouldn't manipulate real DOM in your components. 无论如何,在Angular中,您不应在组件中操纵真实的DOM。 Hence, the use of jQuery is highly debatable, in most cases you should avoid it. 因此, jQuery的使用值得商bat,在大多数情况下,应避免使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM