如何防止jquery覆盖“this” [英] How to prevent jquery to override "this"

查看:72
本文介绍了如何防止jquery覆盖“this”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有以下课程:

I have the following class in javascript:

function User(aJid){
    this.jid = aJid;
    this.name = '';
    this.uni = '';
    this.edad = '';
    this.foto = '';
    this.avatar = '';
    this.initialize2 = function(){

        $('#edit_vcards').on('click', '#enviar_vcard', function(){
            //alert("enviando...");
            console.log(this);
        });
    };

正如你所看到的,我有一个方法initialize2,它将一个函数绑定到DOM中的一些元素。在那里我做一个 console.log(this),它打印我们绑定方法的DOM元素,而不是执行方法的对象 initialize2 。如何从该功能访问该对象?
如果绑定的函数的范围是整个DOM而不是对象,那就好了。无论如何要做我想做的事情?

As you can see I have a method "initialize2" that binds a function to some elements in the DOM. In there I do a console.log(this) which prints the DOM element we binded the method to and not the object that is executing the method initialize2. How can I have access to that object from that function? Its like if the scope of the function binded is the whole DOM and not the object. Anyway to do what Im trying to do ?

推荐答案

function User(aJid){
    this.jid = aJid;
    this.name = '';
    this.uni = '';
    this.edad = '';
    this.foto = '';
    this.avatar = '';
    this.initialize2 = function(){
    var that = this;  //store a reference to maintain scope

        $('#edit_vcards').on('click', '#enviar_vcard', function(){
            //alert("enviando...");
            console.log(that);  //use that variable here
        });
    };

这篇关于如何防止jquery覆盖“this”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆