最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Deathmatch: Self Executing Anonymous Function -vs- "new function" - Stack Overflow

programmeradmin1浏览0评论

Answer Embedded Below in UPDATE 2/ANSWER

Thanks to Joseph for helping me find the answer (even though I don't like it =).

ORIGINAL QUESTION

While doing some research on best practices when using Namepsaces in JavaScript, I came across this definition of the "Model Pattern": / .

I've been generally using this pattern since I saw it in YUI2 years ago, and this article gives a nice overview of the concept. But what it does not touch on is why "Self Executing Anonymous Functions" are used in place of "new function". This was asked in the comments, but was not well described by the author. As this article is 4+ years old (and I've not found the answer elsewhere online) I thought I'd bring it here.

It's already within a closure, so? (see: Why is this function wrapped in parentheses, followed by parentheses? which also doesn't answer my question =).

Assuming the following setup code..

var MyNamespace = window.MyNamespace || {};

Which of these is preferred and why?

MyNamespace.UsingNew = new function() {
    var fnPrivate = function() {
        return "secrets1";
    };

    this.property = "value1";
    this.method = function() {
        return "property = " + this.property + ' ' + fnPrivate();
    }
};

MyNamespace.UsingSelfEx = (function() { //# <- Added "pre-parens" suggested by chuckj
    var fnPrivate = function() {
        return "secrets2";
    };
    var fnReturn = {};

    fnReturn.property = "value2";
    fnReturn.method = function() {
        return "property = " + this.property + ' ' + fnPrivate();
    }

    return fnReturn;
})();

UPDATE:

It seems that like jQuery, all the cool kids are using "Self Executing Anonymous Functions" (SEAF)! But I just don't get this, as I find it much cleaner to use the .UsingNew approach as you expose the public functions at definition (rather than below in a return that needs to be maintained separately or being forced to use the inline object notation).

The argument for not needing "that = this" doesn't hold water for me for a number of reasons:

  • In order to avoid "var that = this" you end up either making a "var obj" plus a return statement (having to maint. a separate definition of what is public) or being forced to use the inline object notation (return {1,2,3}) for your public properties/methods.
  • You could always make a private variable of "var that = this" at the top of the class/namespace and use "that" throughout.

Now... I suppose my development style may well make the .UsingNew pattern much easier to manage. My "private" functions are almost always "static" in nature, so I need to pass in the context anyway (supplanting the need for "this"). I have also taken up the habit of using an "abbreviation" namespace, so when I do need access to "this" I simply refer to the full object via the "abbreviation" namespace rather than via it's full path. E.G.:

var PrivateFunct = function() {
    var rThis = Cn._.val; //# The abbreviated form of Cn.Renderer.Form.Validation
    //...
};

or if it's a Private Static Function...

var PrivateStaticFunct = function(oContext) {
    //...
};

Other then the reasons given above, I personally find the .UsingNew approach much more readable in the source. I've got a pretty extensive codebase that uses the .UsingNew pattern here: .Web/js/Cn/ with the Validation functionality probably the easiest to get your head around in 1 quick read thru. I also use some SEAF functions (see ErrorMessages.js.aspx) but only when they make sense.

I could not imagine having to maintain separate returns to expose the public interfaces at the bottom! Yuck!

Now, don't get me wrong, there are a number of places where a SEAF is very useful in order to enforce the closure, but I personally think it's overused within objects.

UPDATE 2:

Upon further reflection (and thanks to an extended discussion with Joseph under his answer) there seems to be some rules that can be applied to this DEATHMATCH:

Per Douglas Crockford (see: JS we hardly new Ya) Anonymous functions should never use the "new" keyword because:

  • It is faster to use an object literal.
  • By using new to invoke the function, the object holds onto a worthless prototype object. That wastes memory with no offsetting advantage. If we do not use the new, we don’t keep the wasted prototype object in the chain. (NOTE: prototype calls come after the constructor definition, and as SEAF or "new" anonymous functions are fired imminently one cannot use prototype with them)
  • It requires less code to use an object literal. (while true, I have to disagree as I hate the object literal notation, I'd much prefer to use ;'s rather then ,'s as it's more readable).
  • It is never a good idea to put new directly in front of function. For example, new function provides no advantage in constructing new objects.

So it seems the meat and potatoes of the matter is this: SEAF's are preferable to var obj = new function() {...}; due to speed and less overhead (no unneeded prototype object). What you have to suffer through is the fact that you are forced to use object literal notation (so ,'s rather than ;'s between your public members) or to maintain a separate list of public objects in a return object.

SEAF's are not advisable when you are intending the function to work as an object constructor as instanceof will not work as expected (see: creating objects from JS closure: should i use the “new” keyword?).

ANSWER:

  • If it's an anonymous function intended to function as a Singleton/Global Static Instance, use SEAF.
  • If you are intending it to function as a Constructor (to potentially represent multiple objects) or you are using .prototype, use a "standard" function definition and invoke with "new", e.g.:

    function PseudoClass1() {}

    var PseudoClass2 = function() {};

    var myClass1 = new PseudoClass1();

    var myClass2 = new PseudoClass2();

I have to say, I am not happy with this answer ;) I find the .UsingNew pattern MUCH more readable in the codebase, but it is slower and uses more memory then SEAF due to the fact that the unused prototype reference is instantiated and left in the object chain.

Answer Embedded Below in UPDATE 2/ANSWER

Thanks to Joseph for helping me find the answer (even though I don't like it =).

ORIGINAL QUESTION

While doing some research on best practices when using Namepsaces in JavaScript, I came across this definition of the "Model Pattern": http://yuiblog.com/blog/2007/06/12/module-pattern/ .

I've been generally using this pattern since I saw it in YUI2 years ago, and this article gives a nice overview of the concept. But what it does not touch on is why "Self Executing Anonymous Functions" are used in place of "new function". This was asked in the comments, but was not well described by the author. As this article is 4+ years old (and I've not found the answer elsewhere online) I thought I'd bring it here.

It's already within a closure, so? (see: Why is this function wrapped in parentheses, followed by parentheses? which also doesn't answer my question =).

Assuming the following setup code..

var MyNamespace = window.MyNamespace || {};

Which of these is preferred and why?

MyNamespace.UsingNew = new function() {
    var fnPrivate = function() {
        return "secrets1";
    };

    this.property = "value1";
    this.method = function() {
        return "property = " + this.property + ' ' + fnPrivate();
    }
};

MyNamespace.UsingSelfEx = (function() { //# <- Added "pre-parens" suggested by chuckj
    var fnPrivate = function() {
        return "secrets2";
    };
    var fnReturn = {};

    fnReturn.property = "value2";
    fnReturn.method = function() {
        return "property = " + this.property + ' ' + fnPrivate();
    }

    return fnReturn;
})();

UPDATE:

It seems that like jQuery, all the cool kids are using "Self Executing Anonymous Functions" (SEAF)! But I just don't get this, as I find it much cleaner to use the .UsingNew approach as you expose the public functions at definition (rather than below in a return that needs to be maintained separately or being forced to use the inline object notation).

The argument for not needing "that = this" doesn't hold water for me for a number of reasons:

  • In order to avoid "var that = this" you end up either making a "var obj" plus a return statement (having to maint. a separate definition of what is public) or being forced to use the inline object notation (return {1,2,3}) for your public properties/methods.
  • You could always make a private variable of "var that = this" at the top of the class/namespace and use "that" throughout.

Now... I suppose my development style may well make the .UsingNew pattern much easier to manage. My "private" functions are almost always "static" in nature, so I need to pass in the context anyway (supplanting the need for "this"). I have also taken up the habit of using an "abbreviation" namespace, so when I do need access to "this" I simply refer to the full object via the "abbreviation" namespace rather than via it's full path. E.G.:

var PrivateFunct = function() {
    var rThis = Cn._.val; //# The abbreviated form of Cn.Renderer.Form.Validation
    //...
};

or if it's a Private Static Function...

var PrivateStaticFunct = function(oContext) {
    //...
};

Other then the reasons given above, I personally find the .UsingNew approach much more readable in the source. I've got a pretty extensive codebase that uses the .UsingNew pattern here: http://code.google.com/p/cn-namespace/source/browse/Cn.Web/js/Cn/ with the Validation functionality probably the easiest to get your head around in 1 quick read thru. I also use some SEAF functions (see ErrorMessages.js.aspx) but only when they make sense.

I could not imagine having to maintain separate returns to expose the public interfaces at the bottom! Yuck!

Now, don't get me wrong, there are a number of places where a SEAF is very useful in order to enforce the closure, but I personally think it's overused within objects.

UPDATE 2:

Upon further reflection (and thanks to an extended discussion with Joseph under his answer) there seems to be some rules that can be applied to this DEATHMATCH:

Per Douglas Crockford (see: JS we hardly new Ya) Anonymous functions should never use the "new" keyword because:

  • It is faster to use an object literal.
  • By using new to invoke the function, the object holds onto a worthless prototype object. That wastes memory with no offsetting advantage. If we do not use the new, we don’t keep the wasted prototype object in the chain. (NOTE: prototype calls come after the constructor definition, and as SEAF or "new" anonymous functions are fired imminently one cannot use prototype with them)
  • It requires less code to use an object literal. (while true, I have to disagree as I hate the object literal notation, I'd much prefer to use ;'s rather then ,'s as it's more readable).
  • It is never a good idea to put new directly in front of function. For example, new function provides no advantage in constructing new objects.

So it seems the meat and potatoes of the matter is this: SEAF's are preferable to var obj = new function() {...}; due to speed and less overhead (no unneeded prototype object). What you have to suffer through is the fact that you are forced to use object literal notation (so ,'s rather than ;'s between your public members) or to maintain a separate list of public objects in a return object.

SEAF's are not advisable when you are intending the function to work as an object constructor as instanceof will not work as expected (see: creating objects from JS closure: should i use the “new” keyword?).

ANSWER:

  • If it's an anonymous function intended to function as a Singleton/Global Static Instance, use SEAF.
  • If you are intending it to function as a Constructor (to potentially represent multiple objects) or you are using .prototype, use a "standard" function definition and invoke with "new", e.g.:

    function PseudoClass1() {}

    var PseudoClass2 = function() {};

    var myClass1 = new PseudoClass1();

    var myClass2 = new PseudoClass2();

I have to say, I am not happy with this answer ;) I find the .UsingNew pattern MUCH more readable in the codebase, but it is slower and uses more memory then SEAF due to the fact that the unused prototype reference is instantiated and left in the object chain.

Share Improve this question edited May 23, 2017 at 12:25 CommunityBot 11 silver badge asked Mar 20, 2012 at 6:41 CampbelnCampbeln 2,9903 gold badges34 silver badges34 bronze badges 3
  • 1 (Late to the party I know..) A lot of interesting stuff here...since you strongly prefer the UsingNew I don't think the unused prototype alone is sufficient reason to change your approach...it's a very minimal amount of memory (for sake of comparison, it's much more minimal than the amount that coders using the module pattern are willing to sacrifice by not using prototypes.) – Matt Browne Commented May 12, 2013 at 9:18
  • 1 In terms of the anonymous function approach, perhaps it would seem more readable if you called the return variable "self" instead of something like "fnReturn." You could even pass any empty object to the function and have "self" be a parameter; then asside from the return statement and the use of "self" instead of "this", the body of the function would be identical to your first example. – Matt Browne Commented May 12, 2013 at 21:29
  • You should definitely not use new function – Bergi Commented Jan 26, 2015 at 2:11
Add a comment  | 

3 Answers 3

Reset to default 8

For one thing, this pattern:

MyNamespace.UsingNew = new function() {
    var fnPrivate = function() {

        //what's this in here?

        return "secrets1";
    };

    this.property = "value1";
    this.method = function() {

        //what's this in here?

        return "property = " + this.property + ' ' + fnPrivate();
    }
};
  • uses the "new" keyword to create an instance of an object, which is modeled using a constructor function. forgetting to use "new", you'll end up named making a function MyNamespace.UsingNew() instead of an object.

  • it's a constructor function, and not yet an object's instance (until you build it using new). you need to use "this" to pertain the object that it will become. it just add's problems to scope, especially when you nest more functions in it, and the value of "this" will change from time to time (and you won't see it coming until the console tell's you). familiar with the self=this or that=this to save the value of "this"? it's pretty much seen when using this pattern

on the otherhand, the next pattern is somewhat better (for me) since:

  • you don't need to use "new" since it returns an object.

  • not using "this" since it already returns an object. you don't even need "this".

also, i prefer constructing the other pattern this way:

ns.myobj = (function(){

    //private
    var _privateProp = '';
    var _privateMeth = function(){};

    //public
    var publicProp = '';
    var publicMeth = function(){};

    //expose public
    return {
        prop:publicProp,
        meth:publicMeth
    };
}());

Both are almost identical and should have relatively the same performance characteristics. It is just a matter of style. I, personally, favor the second one but it is written a bit funky. I would write it,

MyNamespace.UsingSelfEx = (function () {
    function fnPrivate() {
        return "secrets2";
    }
    return {
        property: "value2";
        method: function () { 
            return "property = " + this.property + " " + fnPrivate();
        }
    }
})();

You don't really need the parens around the function but self-executing functions normally have them and lets the reader know, at the beginning, that this is a self executing function.

I've seen this and I liked it

var MyThing = (function(){

    function MyThing(args){
    }

    MyThing.prototype = {
        prototypeMethod: function() {}
    };

    return MyThing;
})();

You can also do this

MyThing.create = function(args){
    return new MyThing(args);
}

Usually it is enclosed in an another self invoking function. In order to avoid naming collisions.

(function({

})(window);

And the window object is passed as an argument, to assign it to an upper scope.

window.MyThing = MyThing;

In this example you can use, static variables,private etc.

发布评论

评论列表(0)

  1. 暂无评论