如何从javascript闭包内调用属性

时间:2012-07-20 00:14:24

标签: javascript

我在方法getresult()中有一个javascript闭包。我想调用对象quo中的属性。

var quo = function (test) {
        talk: function () {
            return 'yes';
        }
        return {
            getresult: function () {
                return quo.talk();
            }
        }
    }
var myQuo = quo('hi');
document.write(myQuo.getresult());

getresult()内部,如何调用属性talk

2 个答案:

答案 0 :(得分:4)

你的语法错了,你不能从现有的引用中调用talk,无法从外部访问talk,如果你想从quo调用talk,那么你必须在返回的对象中添加对它的引用

var quo = function (test) {
    function talk() {
        return 'yes';
    }
    return {
        getresult: function () {
            return talk();
        },
        talk: talk
    }
}

答案 1 :(得分:0)

quo不是对象,而是一个简单的函数,并且没有属性(从技术上讲,它可以有,但这里不适用)。

var quo = function(test) {
     function talk() {
          return 'yes';
     }
     /* OR:
     var talk = function() {
          return 'yes';
     }; */

     return {
         getresult: function() {
             // in here, "quo" references the closure function.
             // "talk" references the local (function) variable of that "quo" function
             return talk();
         }
     }
}
var myQuo = quo('hi');

myQuo.getresult(); // "yes"

如果您想在talk对象上获取属性“myQuo”,则需要使用此属性:

var quo = function(test) {
    return {
        talk: function() {
             return 'yes';
        },
        getresult: function() {
             // in here, "quo" references the closure.
             // "this" references current context object,
             // which would be the the object we just return (and assign to "myQuo")
             return this.talk();
        }
    };
}
var myQuo = quo('hi');

myQuo.getresult(); // "yes"

详细了解this keyword at MDN