Is it possible to realize the function of self-awareness without an external input

Background

I want the function to track its own state:

var myObject = {

    myFunction: function () {

        var myself = this.myFunction;
        var firstTime = Boolean(!myself.lastRetry);

        if (firstTime) {

            myself.lastRetry = Date.now();
            return true;
        }

        // some more code

    }
}

The problem with the code above is that the value thiswill depend on the site of the function call. I want the function to be able to refer to itself without using:

  • myObject.myFunction
  • .bind()
  • .apply()
  • .call()

Question

Is it possible to give a function of such self-awareness, independent of its call site, and without any help from external links to it?

+4
source share
3 answers

If you want to save this state in an instance of a function, give the function a name and use that name inside it:

var myObject = {

    myFunction: function theFunctionName() {
    //                   ^^^^^^^^^^^^^^^--------------------- name
        var firstTime = Boolean(!theFunctionName.lastRetry);
    //                           ^--------------------------- using it
        if (firstTime) {

            theFunctionName.lastRetry = Date.now();
    //      ^------------------------------------------------ using it
            return true;
        }

        // some more code

    }
};

, . ( function (), . ( , , , . .)

( ). NFE, , JavaScript, . (IE8 - , : .)

, - , IIFE:

var myObject = (function(){
    var lastRetry = null;
    return {
        myFunction: function() {
            var firstTime = Boolean(!lastRetry);
            if (firstTime) {

                lastRetry = Date.now();
                return true;
            }

            // some more code

        }
    };
})();

lastRetry . ( IE8, XP.:-))


: ! ,

var firstTime = Boolean(!theFunctionName.lastRetry);

... :

var firstTime = !theFunctionName.lastRetry;

... . ( , - .)

+8

, , . ...

var obj = {
    doThings:function doThingsInternal(arg1, arg2) {
        console.log(arg1, arg2);
        for (var arg in doThingsInternal.arguments) {
            console.log(arg);
        }
    }
};

obj.doThings('John', 'Doe');
0

, . , . . , / ! -

    var myObject = {

    myFunction: function () {
       // Whatever you wanna do on the first call...
       // ...
       // And then...
       this.myFunction = function(){
         // Change the definition to whatever it should do
         // in the subsequent calls.
       }
       // return the first call value.
    }
};

, .

0
source

All Articles