简体   繁体   English

如何从javascript闭包内调用属性

[英]How do I call a property from inside a javascript closure

I have a javascript closure and inside the method getresult() . 我有一个javascript闭包,并在方法getresult() I want to call a property in the object quo . 我想调用该对象的属性quo

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

From inside getresult() , how can I call the property talk ? 从内部getresult()我怎么能叫物业talk

your syntax is wrong, and you cant call talk from the quo reference, talk is not accessible from the outside, if you wanna call talk from quo then you have to add a reference to it in your returned object 你的语法错了,你不能从现有的引用中调用talk,无法从外部访问talk,如果你想从quo调用talk,那么你必须在返回的对象中添加对它的引用

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

quo is no object, but a simple function, and has no properties (technically, it could have, but that does not apply here). 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"

If you want to get a property " talk " on the myQuo object, you would need to use this: 如果你想在myQuo对象上获得属性“ talk ”,你需要使用:

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"

Read more on the this keyword at MDN . 在MDN上阅读有关this关键字的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM