Ani*_*ish 0 javascript jquery angular
我试图在jQuery函数内调用一个函数。但是我无法使用'this'范围,因为它是指HTMLElement。
import { Component, Input } from '@angular/core';
import { Injectable } from '@angular/core';
import * as $ from 'jquery';
@Injectable()
export class ChatService {
public chatObj : SomeChatObject;
constructor() { }
disconnect(){
console.log("Chat Disconnected");
}
beforeReload = $(window).bind("beforeunload",function(){
//here 'this' is referred to HTML element. So i am not able to call the disconnect method.
this.disconnect();
});
}
Run Code Online (Sandbox Code Playgroud)
我无法访问jQuery函数中的“断开连接”方法。我如何调用“断开连接”方法。
请尝试以下。
beforeReload = $(window).bind("beforeunload",() => {
//here 'this' is referred to HTML element. So i am not able to call the disconnect method.
this.disconnect();
});
Run Code Online (Sandbox Code Playgroud)
尝试将function定义为() => {}而不是function() {}。因为this是指其最接近function或class。您的情况this是指其最接近的功能。尝试使用() => {}转义函数参考。