Search code examples
javascriptfunctionobject-literalfunction-prototypes

Literal object and function constructor


I took this test on http://jsperf.com/literal-obj-vs-function-obj and Literal wins on FF6, Opera 10, IE8, but the Function method faster on Chrome 13.0.782.112, so which one is a better method to use?

var A = {
    aa : function(){
        var i, j=[];
        var arr = ['Literal', 'Function'];
        for (i = 0; i < arr.length; i++){
            j[i] = arr[i];
        }
       return j[0];
    }
};
var A1 = A;
var A2 = A1;
A1.foo = ' Test';
alert(A1.aa() + A2.foo);

//Function test
function B(){
    this.bb = function(){
        var i, j=[];
        var arr = ['Literal', 'Function'];
        for (i = 0; i < arr.length; i++){
            j[i] = arr[i];
        }
        return j[1];
    }
}
var B1 = new B();
var B2 = new B();
B.prototype.foo = ' Test';
alert(B1.bb() + B2.foo);

Solution

  • To tell you the truth, the best that I have found is a mix:

    function C() {
        var i, j = [],
            foo;
    
        return {
            bb: function() {
    
                var arr = ['Literal', 'Function'];
                for (i = 0; i < arr.length; i++) {
                    j[i] = arr[i];
                }
                return j[1];
            },
            setFoo: function(val) {
                foo = val;
            },
            getFoo: function() {
                return foo;
            }
        }
    }
    var C1 = C();
    var C2 = C();
    C2.setFoo(' Test');
    console.log(C1.bb(), C2.getFoo());