gpt4 book ai didi

javascript - Angular2 - OnInit 访问函数

转载 作者:行者123 更新时间:2023-12-02 14:22:02 26 4
gpt4 key购买 nike

我不断遇到 OnInit 访问同一组件类中的函数的问题。

我的基本设置如下:

import {Component, OnInit} from '@angular/core';
...
export class AppComponent implements OnInit {

login(){...}

ngOnInit() {

this.login(); //1

document.onkeypress = function(e){
if ( document.body === document.activeElement ) {
this.login(); //2
}

};

1 将按预期在页面加载时触发登录函数,但 2 提示登录不是函数。如何正确访问 AppComponent 中的登录功能?

最佳答案

这与范围界定有关。当您从 onkeypress 回调中调用 this.login 时,this 引用了全局对象,因此 this.login 是等于 window.login 在你的情况下是未定义的

可能的解决方案

缓存

var _this = this;
document.onkeypress = function(e){
if ( document.body === document.activeElement ) {
_this.login(); //2
}

};

使用 .bind 显式设置上下文

document.onkeypress = function(e){
if ( document.body === document.activeElement ) {
this.login(); //2
}

}.bind(this);

使用 ES6 箭头函数()=>{}

document.onkeypress = (e) => {
if ( document.body === document.activeElement ) {
this.login(); //2
}

};

关于javascript - Angular2 - OnInit 访问函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38577749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com