javascript - 如何从 JavaScript 中同一对象中的另一个方法调用方法?

标签 javascript jquery oop

我刚刚开始使用 OO javascript,所以请多多包涵。

这个有效:

var myObj = {
     foo : function() {
            alert('hello');
            this.bar();
     },
     bar: function() {
            alert('world');
     }
}

但是,如果我在“foo”方法中的 hello 警报之后做了一些其他事情,那么“this”的含义将从对象变为我上次选择的任何内容,因此使用 this.bar()不执行类中的其他方法。

所以我尝试将“this”缓存在一个变量中,如下所示:

var myObj = {
     publicVars: {
            theObj : this
     },
     foo : function() {
            alert('hello');
            publicVars.theObj.bar();
     },
     bar: function() {
            alert('world');
     }
}

但这也没有用。那么解决方案是什么?

编辑

这是我的实际代码:

var formObj = {

     validate : function(theForm) {
            $('input, textarea', theForm).each(function() {
                 var valueLength = $(this).val().length;
                 if (valueLength === 0) {
                        $(this).addClass('invalid');
                        this.listenForInput($(this)); // <!------- this isn't working
                 }
            });
     },
     listenForInput : function(theField) {
//          theField.keyup(function() {
//               if ($(this).val().length > 0) {
//                      theField.removeClass('invalid');
//               }
//          });
            alert('I work!!!!');
     }

} // end obj

最佳答案

正如我在评论中所说,您必须在函数内部保留一个引用:

validate: function(theForm) {
    var self = this;
    $('input, textarea', theForm).each(function() {
        var valueLength = $(this).val().length;
        if (valueLength === 0) {
           $(this).addClass('invalid');
           self.listenForInput($(this));
        }
    });
},

您正在将一个函数传递给each。在此回调中,this 引用 DOM 元素。这就是将它传递给 jQuery ($(this)) 以便能够对该元素调用 jQuery 方法的原因。它也不能引用 formObj!


this 指的是什么 如何 函数被调用,每个函数都有自己的 this(Mozilla documention 描述 this 更详细)。

如果您使用 formObj.validate() 调用 validate,则 this 引用 formObj

jQuery documentation for each状态:

More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

关于javascript - 如何从 JavaScript 中同一对象中的另一个方法调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7155227/

相关文章:

javascript - d3 v4 获取条形图工具提示的数据

javascript - 如何使用 Highcharts 指向数据中第二个索引的范围(dataClasses)?

javascript - 在使用 jQuery 打开时,将更多选项添加到选择下拉列表中

javascript - 使用 jquery then() 打印 html 和 json 结果

c++ - 如何声明运算符重载 < 以在需要时在类变量之间动态切换?

c# - 通过通用接口(interface)封装的正确方法

c++ - 编译时消除虚拟表?

javascript - 无法检查一个正方形是否为空 tictactoe 游戏 jquery

javascript - 下载文件并在单击链接时滚动到底部 div

jquery - Div 在向左/向右过渡时越过其他 div