Definition of functions after return

I am currently reading the John Papa AngularJS style guide and saw the code :

function dataService() {
    var someValue = '';
    var service = {
        save: save,
        someValue: someValue,
        validate: validate
    };
    return service;

    ////////////

    function save() {
        /* */
    };

    function validate() {
        /* */
    };
}

You can see that the functions saveand are validatedefined after the function returned the value. How it works? Is it standard and works in all browsers (say, from IE 6)?

+4
source share
1 answer

You can see that the functions saveand are validatedefined after the function returned the value.

, , , , , . "" (- var, ).

(, , eval), , , : . save validate , , , , return.

, JavaScript (, dataService), :

  • this
  • ( env)
  • [[Scope]] env ( )
  • ( bindings), , ( , , )
  • , bindings ,
  • bindings
  • , bindings
  • arguments, bindings
  • , var, bindings ( ) undefined

§10.4.1 , . ( , , , ... turgid...) , § 10 1999 , , .

(, IE 6)?

. , (, 2005 ) , ( IE6), . , , :

doSomething();

function doSomething() {
    // ....
}

... .


"" . save validate , , return — :

// It wouldn't work like this, for instance
function dataService() {
    var someValue = '';
    var service = {
        save: save,             // `save` has the value `undefined` at this point
        someValue: someValue,
        validate: validate      // So does `validate`
    };
    return service;

    ////////////

    var save = function() {      // Now this is a function expression
        /* */
    };

    var validate = function() {  // This too
        /* */
    };
}

save validate ( 9 ), undefined, " .

+8

All Articles