Javascript原型Class Literals最佳实践

时间:2011-03-15 16:02:33

标签: javascript prototype literals

我是Javascript的新手,所以我想知道以下代码是否是一个好习惯。

CustomClass = function(var1, var2) {
    this.var1 = var1;
    this.var2 = var2;
};
CustomClass.prototype.aMethod = function() {
    console.log("my class method");
};

// Intend as main .js object, if that makes sense
var m = {
    object1:CustomClass.prototype,
    object2:CustomClass.prototype,

    initObjects:function() {
        m.object1 = new CustomClass( value1, value2 );
        m.object1.aMethod();
        m.object2 = new CustomClass( value1, value2 );
        m.object2.aMethod();
    }
};

或者我应该在“s”文字中创建自定义类吗?

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

关于你的实际代码:

// globally scoped. Only avoided with closures and hoisting as shown below
// Also doesn't really make sense to define CustomClass on m unless you want
// To use it directly instead of through a factory function
CustomClass = function(var1, var2) {
    this.var1 = var1;
    this.var2 = var2;
};
CustomClass.prototype.aMethod = function() {
    console.log("my class method");
};

// Intend as main .js object, if that makes sense
var m = {
    // No reason to initialise them to the prototype. Doesn't really make sense
    // m can be edited without needing to intialise object1 or object2 at all
    object1:CustomClass.prototype,
    object2:CustomClass.prototype,

    initObjects:function() {
        m.object1 = new CustomClass( value1, value2 );
        m.object1.aMethod();
        m.object2 = new CustomClass( value1, value2 );
        m.object2.aMethod();
    }
};

可能更多地基于闭合和提升的不同模式。这需要更具功能性的方法,并远离标准的经典继承。

// Create closure to localise scope.
(function() {
    // global object to store anything that will be hoisted to global scope
    var global = {};

    // Constructor that uses local objects and defines methods on
    // this directly.
    var CustomClass = function(_a,_b) {
         var a = _a;
         var b = _b;

         this.method = function() { console.log("foo"); }
    }

    // init function will be hoisted to global scope.
    global.init = function() {
         global.object1 = new CustomClass( v1, v2 );
         object1.method();
         global.object2 = new CustomClass( v1, v2 );
         object2.method();
    }

    // Hoist you global object into the global variable "m" on window.
    window.m = global;
}());

当然你丢失了原型链,所以你必须使用更多的对象组合而不是对象继承,这也是一个较小的速度。如果您创建1000多个对象

,速度的损失真的很明显