Javascript 原型类文字最佳实践
我是 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”文字中创建自定义类?
任何帮助将不胜感激
I am new to Javascript, so I wonder if the following code is a good practice.
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();
}
};
Or should I create my custom class inside the "s" literal?
Any help will be much appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
至于您的实际代码:
可能更多地基于闭包和提升来使用不同的模式。这采用了更实用的方法,并远离了标准的经典继承。
当然,您会丢失原型链,因此必须使用更多的对象组合而不是对象继承,这也会稍微慢一些。仅当您创建 1000 多个对象时,速度损失才会真正明显
As to your actual code:
A different pattern that might be of use based more on closures and hoisting. This takes a more functional approach and moves away from standard classical inheritance.
Of course you lose the prototype chain so your must use a lot more object composition instead of object inheritance and this is also slower by a small amount. The loss of speed is only really noticable if your creating 1000+ objects