小编Pam*_*Pam的帖子

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

我刚刚开始使用OO javascript,所以请耐心等待.

这有效:

var myObj = {
     foo : function() {
            alert('hello');
            this.bar();
     },
     bar: function() {
            alert('world');
     }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我在"foo"方法中的hello警告之后执行其他操作,则"this"的含义会从对象更改为我上次选择的任何内容,因此使用this.bar()不会执行类中的其他方法.

所以我试着在这样的变量中缓存"this":

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

但这也不起作用.那么解决方案是什么?

编辑

这是我的实际代码:

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
                 }
            }); …
Run Code Online (Sandbox Code Playgroud)

javascript oop jquery

5
推荐指数
1
解决办法
1245
查看次数

标签 统计

javascript ×1

jquery ×1

oop ×1