开发者

Invoke public function from internal/private function?

Just wondering if I'm missing something or not but I attempted to do the following:

(function() {
    var thing = function() {
        var doIt = function() {
            console.log("just do it");
            this.updateValue(5);
        };

        return {
            updateValue: function(val) {
                console.log('updating value: ' + val);
            },

            go: function() {
                doIt();
            }
        }
    };

    var t = thing();
    t.go();
}())

This results in "just do it" showing up in the console followed by an error b/c it says "updateValue" is not a function.

I was wondering, can an internal/private function (e.g. "doIt") invoke a public function (e.g. "updateValue")? Perhaps this is just bad design and you should never really want to do this and I've actually 开发者_StackOverflowrefactored my code to avoid/not do this but I was curious if it was possible.

Thanks in advance.


Either use call/apply to explicitly specify the context for this (like @SLaks and @Alnitak) mentioned or else define the function at the beginning and then add it as a property to the returned object:

var thing = function() {
    var updateValue = function () { /* */ },
        doIt = function() {
            console.log("just do it");
            updateValue(5);
    };

    return {
        updateValue: updateValue, // minor duplication here
        go: function() {
            doIt();
        }
    };
};

If the minor duplication annoys you, you can also do this:

var thing = function() {
    var exposed = {
        updateValue: function(val) {
            console.log('updating value: ' + val);
        },
        go: function() {
            doIt();
        }
    }, doIt = function() {
        console.log("just do it");
        exposed.updateValue(5);
    };

    return exposed;
};


Writing doIt(), calls the function in the global context, so this is the window object.

You need to write doIt.call(this) to pass your this as the context for doIt.


Per @SLaks answer, this is incorrect when invoked by doIt().

Instead, try:

doIt.call(this);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜