在JavaScript中,这3个示例中的哪一个具有最佳性能

时间:2013-07-26 08:22:31

标签: javascript object closures prototype

这三个函数/对象可以用于相同的目的,我将创建每个对象的新实例。我将创造1000个,所以我想知道哪个具有最佳性能。

jelly1 = new JellyFish();
jelly2 = new JellyFish2();
jelly3 = new JellyFish3();


//jellyfish object 3
function JellyFish3() {
    this.color = "blue";
    this.size = "medium";
    this.move = function (direction) {
        console.log("moving to " + direction);
        return direction;
    };
}

// jellyfish object 2
function JellyFish2() {};
// constructor
(function (instance) {
    instance.color = "blue";
    instance.size = "medium";
    instance.move = function (direction) {
        console.log("moving to " + direction);
        return direction;
    };
})(JellyFish2.prototype);

// jellyfish object 1
function JellyFish() {
    // constructor
    (function (instance) {
        instance.color = "blue";
        instance.size = "medium";
        instance.move = function (direction) {
            console.log("moving to " + direction);
            return direction;
        };
    })(JellyFish.prototype);
};

1 个答案:

答案 0 :(得分:2)

创建50个构造函数...... JellyFish1获胜! http://jsperf.com/jellyfish

创建50个实例...... JellyFish2获胜! http://jsperf.com/jellyfish-instance