Javascript 在jquery上下文中调用this.function

Javascript 在jquery上下文中调用this.function,javascript,jquery,prototype,this,Javascript,Jquery,Prototype,This,我正试图通过jquery范围内的引用调用函数: var Person = function(){ this.hello = function(){ console.log("hello!"); } this.jump = function(){ $('.jump').on('click', function(){ this.hello(); }); } } 那么我会: var p =

我正试图通过jquery范围内的
引用调用函数:

var Person = function(){

    this.hello = function(){
        console.log("hello!");
    }

    this.jump = function(){
        $('.jump').on('click', function(){
            this.hello();
        });
    }

}
那么我会:

var p = new Person();
当我单击
.jump
元素时,控制台会打印一个错误,说明
hello不是一个函数
。我不确定这里发生了什么,我假设
this
正在尝试调用jquery内部的函数(不确定)

所以,在谷歌上搜索一下,我发现这个功能在我的情况下可能会很有用,但每次我试图理解它时,我的脑袋都想爆炸

试试这个

var self = this;


 this.jump = function(){
        $('.jump').on('click', function(){
            self.hello();
        });
    }
试试这个

var self = this;


 this.jump = function(){
        $('.jump').on('click', function(){
            self.hello();
        });
    }
像这样使用
$.proxy()

var Person = function(){

    this.hello = function(){
        console.log("hello!");
    }

    this.jump = function(){
        $('.jump').on(
            'click',
            $.proxy(
                function() {
                    this.hello();
                },
                this
            )
        );
    }
}
this
作为第二个参数传递给
$。proxy()
在第一个参数中定义的函数内将该上下文作为
this
的值发送。

使用
$.proxy()
如下:

var Person = function(){

    this.hello = function(){
        console.log("hello!");
    }

    this.jump = function(){
        $('.jump').on(
            'click',
            $.proxy(
                function() {
                    this.hello();
                },
                this
            )
        );
    }
}
this
作为第二个参数传递给
$。proxy()
将该上下文作为第一个参数中定义的函数中的
this
的值发送。

当在onclick中引用“this”时,默认情况下,它引用在event.target的值中找到的DOM元素

$('.jump').on('click', function(event) {
     this.hello() /// <<-- this == event.target =~ $('.jump')
}
当您在onclick中引用“this”时,默认情况下,它引用在event.target的值中找到的DOM元素

$('.jump').on('click', function(event) {
     this.hello() /// <<-- this == event.target =~ $('.jump')
}

我认为这个答案很优雅。我认为这个答案很优雅。在第一个例子中,应该澄清的是,默认情况下,代码< > <代码>是指在代码<事件>目标>代码>中找到的DOM元素。在第一个例子中,应该澄清的是,默认情况下,
引用在
event.target的值中找到的DOM元素。