0

If I know that I only will create one instance of the MyClass function below, which of my two snippets below would you prefer? Should I stick with the latter, even though I know that I'll only create one instance of the function?

I know that prototype is useful from a performance perspective when sharing methods across all instances of a function, but in this case I would like to hear your input.

var MyClass = (function () {

    var cls = function () { };

    cls.prototype = {

        init: function(data){

        }
    };

    return cls;
})();

vs

var MyClass = (function () {

    var cls = function () { 

        this.init = function(data){

        }
    };

    return cls;
})();
4

1 回答 1

1

Your second code snippet is a syntax error, you're trying to put a property initializer where a statement is expected. (Not anymore)

If you're only going to have a single object that you need the init function on, then:

var MyObject = {
    init: function(data) {
        // ...
    }
};

Then you don't even need to call a function to create it, it's already there.

If you want to have truly private variables and such (which I assume is the reason for your outer anonymous functions), then:

var MyObject = (function() {
    var trulyPrivateDataHere;

    return {
        init: function(data) {
            // ...
        }
    };
})();

I prefer this because it's clear and direct: You're creating the actual object. I don't see any need for a constructor function if you're only ever going to create a single instance.

But if it has to be a constructor function, I guess I'd very marginally prefer your second option, because it's simpler, and simple is good barring the need for complexity.

于 2013-03-30T12:07:28.850 回答