Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - JavaScript闭包的实际用途是什么?(What is a practical use for a closure in JavaScript?)

I'm trying my hardest to wrap my head around JavaScript closures.(我正在竭尽全力围绕JavaScript闭包。)

I get that by returning an inner function, it will have access to any variable defined in its immediate parent.(通过返回内部函数,我可以访问其直接父级中定义的任何变量。)

Where would this be useful to me?(这对我有什么用?)

Perhaps I haven't quite got my head around it yet.(也许我还没有完全明白这一点。) Most of the examples I have seen online don't provide any real world code, just vague examples.(我在网上看到的大多数示例都没有提供任何真实的代码,只是模糊的示例。)

Can someone show me a real world use of a closure?(有人可以告诉我现实世界中使用闭包吗?)

Is this one, for example?(例如,这是吗?)

var warnUser = function (msg) {
    var calledCount = 0;
    return function() {
       calledCount++;
       alert(msg + '
You have been warned ' + calledCount + ' times.');
    };
};

var warnForTamper = warnUser('You can not tamper with our HTML.');
warnForTamper();
warnForTamper();
  ask by alex translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I've used closures to do things like:(我用闭包来做类似的事情:)

a = (function () {
    var privatefunction = function () {
        alert('hello');
    }

    return {
        publicfunction : function () {
            privatefunction();
        }
    }
})();

As you can see there, a is now an object, with a method publicfunction ( a.publicfunction() ) which calls privatefunction , which only exists inside the closure.(如您所见, a现在是一个对象,它具有方法publicfunctiona.publicfunction() ),该方法调用privatefunction ,该方法仅存在于闭包内部。)

You can NOT call privatefunction directly (ie a.privatefunction() ), just publicfunction() .(你不能privatefunction直接(即a.privatefunction()只是publicfunction())

Its a minimal example but maybe you can see uses to it?(它是一个最小的示例,但也许您可以看到它的用处?)

We used this to enforce public/private methods.(我们使用它来强制执行公共/私有方法。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...