创建"实例的最佳方式"在JS中

时间:2014-06-20 18:26:55

标签: javascript oop

最近,在一些js游戏制作博客和网站等我已经看到了一个新的约定,用于创建某种"实例"。它看起来像这样:

var newCharacter = function (x, y) {
    return {
        x: x,
        y: y,

        width: 50,
        height: 50,

        update: function () {
            //do update stuff here
        }
    };
};

var myCharacter = newCharacter(20, 30); //create "instance"

与传统方式相反:

 var Character = function (x, y) {
    this.x = x;
    this.y = y;

    this.width = 50;
    this.height = 50;

    this.update = function () {
        //do update stuff here
    };
};

var myCharacter = new Character(20, 30); //create intance

我很好奇使用第一种方式的优点是什么。它更有效率,语义还是更快?

0 个答案:

没有答案