【问题标题】:How can I access an Angular class variable without using `this`? [duplicate]如何在不使用 `this` 的情况下访问 Angular 类变量? [复制]
【发布时间】:2018-12-18 19:06:04
【问题描述】:

有什么方法可以在不使用this. 的情况下从StartPage 类访问变量MyVariable?我问的原因是我需要在函数中引用它,而this 在那里不起作用。我从here 知道我可以使用=> {...,但这并不总是适合我。我该怎么做?

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-start',
  templateUrl: './start.page.html',
  styleUrls: ['./start.page.scss'],
})
export class StartPage implements OnInit {

  constructor() {}

  MyVariable = "Value";

  ngOnInit() {
   console.log(MyVariable); 
   //anyway to use MyVariable without `this.` prefix?
  }

}

【问题讨论】:

  • bind(this) 适合你吗?
  • 您是否尝试将其传递给ngOnInit
  • The reason I am asking is that I need to reference this in a function this,或者您可能正在使用 lambda 但您不知道如何使用。
  • 考虑使用this。你的队友和未来的自己会感谢你。如果您在使用特定箭头功能时遇到问题,请发布它的代码,我们可以提供帮助。不应该出现箭头函数“不起作用”的情况。

标签: javascript angular typescript


【解决方案1】:

I need to reference this in a function, and this does not work

我认为这是因为您尝试从回调函数(订阅、setTimeout 或类似函数)访问,而这未在上下文中定义。要访问 this 作为 StartPage 类的引用,您必须将 this 的引用绑定到函数,例如:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-start',
  templateUrl: './start.page.html',
  styleUrls: ['./start.page.scss'],
})
export class StartPage implements OnInit {

  constructor() {}

  MyVariable = "Value";

  ngOnInit() {
     this.myFunction().bind(this);
  }

  myFunction(){
     // ...
     this.MyVariable = someValue
     // ...
  }

}

【讨论】:

  • 似乎这样可行。但是还有其他方法可以做到这一点吗?我可以做类似StartPage.MyVariable 的事情吗?
  • @nachshonf 该语法是您访问静态变量的方式。如果你想访问一个实例变量,你必须引用一个实际的实例。
  • @nachshonf StartPage.MyVariable 将类似于一个常量值,而不是对象本身的实例。据我所知,我不知道它是否可以完成
猜你喜欢
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
相关资源
最近更新 更多