开发者

Closures javascript vs java

开发者 https://www.devze.com 2023-04-10 14:46 出处:网络
I am learning javascript and I came across the following code snippet: var outerValue = true; function outerFn(){

I am learning javascript and I came across the following code snippet:

var outerValue = true;

function outerFn(){
  assert( outerFn && outerValue, "These come from the closure." );
}

Insofar as I understand closu开发者_Go百科res in the above context, they allow the outerFn to actually see the outerValue variable.

My question then is: how is this any different from any other programming language - such as java for instance? It is just expected that outerValue's scope will allow outerFn to see it.

added later on:

    var outerValue = true;
    function outerFn() {
        console.log(outerValue);
    }

    function anotherFunction(arg){
        console.log("anotherFunction");
        arg.call(this);
    }

    anotherFunction(outerFn); 

Is this then a better example of a closure?


Understand "clousures" as the ability to change the scope of execution of a function or method. Here's an example where we run the same function by modifying the scope for 'client1' that 'May' and client2 which is 'John'. This is not possible in Java.

<html>
<head>
    <script type="text/javascript" src="jquery-1.5.2.min.js"></script>
    <script type="text/javascript" >

    function assert(condition, message) {
        if (condition) {
            alert(message);
        }
    }

    function testClousures() {
        var client1 = {name: 'Mary', code: 123};
        var client2 = {name: 'John', code: 234};

        function outerFn(){ 
            assert( this.name == 'John', "These come from the closure." );
        }

        // Testing if client is John 
        outerFn.apply(client1);  // Fail
        outerFn.apply(client2);  // Success

    }

    function domReady() {
        $('#btn').click(function(){
            testClousures();
        });
    }
    </script>
</head>
<body onload="domReady()">
<br/>
<input id="btn" type="button" value="Test"></input>
</body>
</hmtl>


Your example does not really illustrate the difference, as you do not define the scope of outerValue. In Javascript, you may nest functions arbitrarily within one another, and closures make sure that inner functions can see outer functions even when invoked after the outer functions are no longer in scope.

In java, nesting functions is not (yet) legal, and thus closures do not even come into play. Having a class field in place of outerValue and a class method in place of your function is different, as the field of course is associated with the scope of the class, not the method.


Imagine the function outerFn() was passed as a callback. Sometime later when it runs, even though outerValue will have fallen out of scope, it will still be accessible within the closure.

HTH

0

精彩评论

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