Moving from `prototype` and `new` to a closure-and-exposure pattern

感情迁移 提交于 2019-12-02 00:19:45

In my experience, the only thing you lose by not using .prototype is memory - each object ends up owning its own copy of the function objects defined therein.

If you only intend instantiating "small" numbers of objects this is not likely to be a big problem.

Regarding your specific questions:

  1. The second comment on that linked article is highly relevant. The author's benchmark is wrong - it's testing the overhead of running a constructor that also declares four inner functions. It's not testing the subsequent performance of those functions.

  2. Your "closure and expose" code sample is not OO, it's just a namespace with some enclosed private variables. Since it doesn't use new it's no use if you ever hope to instantiate objects from it.

  3. I can't answer this - "it depends" is as good an answer as you can get for this.

Answers:

  1. You already answer this question: you loose the prototype chain. (Actually you don't loose it, but your prototype will be always empty). The consequences are:

    • There is a little performance/memory impact, because methods are created for each instance . But it depends a lot on the JavaScript engine, and you should worry about it only if you need to create a big amount of objects.

    • You can't monkey patch instances by modifying the prototype. Not a big issue either, since doing that leads to a maintenance nightmare.

  2. Let me do a small pedantic correction to your question: Is not a matter of "prototype vs closure", in fact the concept of closure is orthogonal to a prototype based language.

    The question is related on how you are going to create objects: define an new object from zero each time, or clone it from a prototype.

    The example that you show about using functions to limit the scope, is a usual practice in JavaScript, and you can continue doing that even if you decide to use prototypes. For example:

    var SomeObj = (function (flag) {
    
        /* all the stuff mentioned above, declared as 'private' `var`s */
    
        var MyObj = function() {}
        MyObj.prototype = {
            flag: flag,
            reset: reset
        };
    
        return {
           expose: function() { return new MyObj(); }
        }
    })();
    

    If you are worried about modularization, take a look into requirejs which is an implementation of a technique called AMD (async module definition). Some people doesn't like AMD and some people love it. My experience with it was positive: it helped me a lot to create a modular JavaScript app for the browser.

  3. There are some libraries to make your life with prototypes easier: composejs, dejavu, and my own barman (yes is a shameless self promotion, but you can look into the source code to see ways of dealing with definitions of objects).

    About patterns: Since you can easily hide object instantiation using factory methods, you can still use new to clone a prototype internally.

Explosion Pills

What else I have lost by foregoing prototype?

I'm sure someone can provide an answer, but I'll at least give it a shot. There are at least two reasons to use prototype:

  1. prototype methods can be used statically
  2. They are created only once

Creating a method as an object member means that it is created for every instance of the object. That's more memory per object, and it slows down object creation (hence your efficiency). People tend to say that prototype methods are like class methods whereas member methods are like object methods, but this is very misleading since methods in the prototype chain can still use the object instance.

You can define the prototype as an object itself, so you may like the syntax better (but it's not all that different):

SomeObj.prototype = {
    method1: function () {},
    method2: function () {}
}

Your argument that it seems less controlled is valid to me. I get that it is weird to have two blocks involved in creating an object. However, it's a bit spurious in that there is nothing stopping someone from overwriting the prototype of your other object anyway.

//Your code
var SomeObj = function (flag) { //...

//Sneaky person's code
delete SomeObj.reset;
SomeObj.prototype.reset = function () { /* what now? */ }

Foregoing new

If you're only going to be creating specific object instances on the fly via {} notation, it's not really different from using new anyway. You would need to use new to create multiple instances of the same object from a class (function) definition. This is not unusual as it applies to any object oriented programming language, and it has to do with reuse.

For your current application, this may work great. However, if you came up with some awesome plugin that was reusable across contexts, it could get annoying to have to rewrite it a lot. I think that you are looking for something like require.js, which allows you to define "modules" that you can import with the require function. You define a module within a define function closure, so you get to keep the constructor and prototype definitions wrapped together anyway, and no one else can touch them until they've imported that module.

Advantages of closure vs. prototype

They are not mutually exclusive:

var attachTo = {};
;(function (attachTo, window, document, undefined) {
    Plugin = function () { /* constructor */ };
    Plugin.prototype = { /* prototype methods */ };

    attachTo.plugin = Plugin;
})(attachTo, window, document);
var plugin = new (attachTo.plugin);

http://jsfiddle.net/ExplosionPIlls/HPjV7/1/

bfavaretto

Question by question:

  1. Basically, having the reset method in the prototype means that all instances of your constructor will share the exact same copy of the method. By creating a local method inside the constructor, you'll have one copy of the method per instance, which will consume more memory (this may become a problem if you have a lot of instances). Other than that, both versions are identical; changing function SomeObj to var SomeObj = function only differs on how SomeObj is hoisted on its parent scope. You said you "gained some privacy with the variable declarations", but I didn't see any private variables there...

  2. With the IIFE approach you mentioned, you'll lose the ability to check if instance instanceof SomeObj.

  3. Not sure if this answers your question, but there is also Object.create, where you can still set the prototype, but get rid of the new keyword. You lose the ability to have constructors, though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!