Javascript 调用Angular 2中jquery函数中组件的函数

Javascript 调用Angular 2中jquery函数中组件的函数,javascript,jquery,angular,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 : SomeCha

我试图在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();
    });

}

我无法访问jQuery函数中的“disconnect”方法。如何调用“disconnect”方法。

您可以绑定函数,给它一个
this

beforeload=$(window.bind(“beforeload”,this.disconnect.bind(this));

beforeReload=$(窗口).bind(“beforeunload”,(函数(){
这个.disconnect();
}).约束(这个);

正如@Yurzui所指出的那样,使用如下箭头函数

beforeReload = $(window).bind("beforeunload",() =>{
     // use the arrow function 
     this.disconnect();
});
否则,如果要继续使用旧语法,请使用

beforeReload = $(window).bind("beforeunload",function(){
     //here 'this' is referred to HTML element. So i am not able to call the disconnect method.
     this.disconnect();
}).bind(this); // check this line
arrow函数在函数内部保留
this
的值 这是ES6中最受欢迎的变化之一

试试下面的

beforeReload = $(window).bind("beforeunload",() => {
     //here 'this' is referred to HTML element. So i am not able to call the disconnect method.
     this.disconnect();
});
尝试将函数定义为
()=>{}
而不是
function(){}
。 因为
引用其最近的
函数
。在您的情况下,
引用其最接近的功能。尝试使用
()=>{}
来转义函数引用。

尝试以下操作:

import { Component, OnInit } from '@angular/core';
declare var jQuery: any;

export class Component implements OnInit {

    constructor() { }

    ngOnInit() {
        jQuery(window).bind('beforeunload', function() {
            this.disconnect();
        }.bind(this));
    }

    disconnect() {
        console.log('disconnect');
    }
}

只需使用箭头功能