Adam Lee
Adam Lee

Reputation: 25738

what's wrong with the following function closure?

in class Vector2 itself, if I use the following

Vector2.prototype.aaaScalar: ( function () {

        var min = new Vector2();

        return function ( minVal) {

            min.set( minVal);

            return this.aaa( min );

        };

    } )(),

It reports min has no set method, but There is set method in Vector2

If changing to the following , everything is OK

Vector2.prototype.aaaScalar: ( function () {

        var min;

        return function ( minVal) {

            if ( min === undefined ) {

                min = new Vector2();

            }

            min.set( minVal );

            return this.aaa( min );

        };

    } )(),

Edit:I checked in the first case, the calling of var min = new Vector2(); does no returns me a fully created object.

Upvotes: 0

Views: 71

Answers (1)

Ghazgkull
Ghazgkull

Reputation: 980

The problem here isn't your closure. Both of your examples are correct as far as the closures go... aaaScalar is getting assigned to the inner function you're returning with the min variable in it's closure.

The difference between the two snippets is timing. In the first example, var min = new Vector2() is executed at the time the aaaScalar property is set... when the IIFE runs. In the second example, min = new Vector2() isn't run until you actually invoke the function assigned to aaaScalar.

I think you'll find that the library you're getting Vector2 from isn't ready at the time aaaScalar is assigned, but it is ready by the time you actually invoke aaaScalar().

Upvotes: 1

Related Questions