2011-03-15 138 views
0

我是Javascript新手,所以我想知道下面的代码是否是一种好的做法。Javascript原型类Literals最佳实践

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”字面内创建自定义类吗?

任何帮助将非常感激

回答

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个对象,速度的损失才真正引人注目

+0

恐怕v1和v2在您的答案中未定义。 –