在jQuery中扩展原型时,如何保持对this关键字的控制? [英] How can I maintain control of the this keyword when extending prototypes in jQuery?

查看:77
本文介绍了在jQuery中扩展原型时,如何保持对this关键字的控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jQuery中实现类似于类的结构,但是当我尝试调用我的一些函数时遇到了一些麻烦。

I'm implementing a class-like structure in jQuery, but I'm having some trouble when I try to call some of my functions.

这是怎么回事结构设置:

This is how the structure is setup:

MyClass = function(name) {
    this.init(name);
}
$.extend(MyClass.prototype, {
    init: function(theName) {
        this.myFunction(); // works
        $('.myclass').each(function(){
            this.myFunction(); // doesn't work
        });
    },
    myFunction = function(){}
});

我遇到的问题是,当我尝试调用我的一个函数时(例如, myFunction())来自jQuery块内部(如上面的 each()构造),我收到错误 myFunction()不是函数

The problem I'm having is that when I try to call one of my functions (e.g., myFunction()) from inside a jQuery block (like the each() construct above), I get the error "myFunction() is not a function."

我认为这与这个关键字在jQuery块中更改其含义,但我不确定。任何帮助将不胜感激!

I think this has something to do with the this keyword changing its meaning inside the jQuery block, but I'm not sure. Any help would be appreciated!

推荐答案

您需要将分配给另一个变量,因为范围的工作原理。

You need to assign this to another variable, because of how scope works.

MyClass = function(name) {
    this.init(name);
}
$.extend(MyClass.prototype, {
    init: function(theName) {
        this.myFunction(); // works
        var that = this;
        $('.myclass').each(function(){
                this.myFunction(); // doesn't work
                that.myFunction(); // should work
        });
    },
    myFunction = function(){}
});

这篇关于在jQuery中扩展原型时,如何保持对this关键字的控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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