What is the correct way to create a Javascript class?

后端 未结 4 792
余生分开走
余生分开走 2021-02-14 19:44

I\'m trying to figure out how to construct my Javascript classes (or singleton objects) correctly.

var obj = new Object();
obj.foo = \'bar\';
obj.method = functi         


        
4条回答
  •  时光说笑
    2021-02-14 20:41

    If you're looking for a practical solution rather than a theoretical one, you better use a framework.

    • Backbone.js has all you need, including mixins and an event system.

    If you need some widgets too, consider

    • qooxdoo
    • ExtJS

    Both of them provide a clean architecture and may be used without widgets, but they require a bit more learning than Backbone.

    The inheritance structure that these frameworks provide feels very much like the common class-based one (think Java). That's because they create special objects internally that merely serve as prototypes for others, and thus take the role of classes.

    For example, when you call Ext.define('MyClass', {extend: 'ParentClass', mixins: foo, ... }), then Ext creates a function "MyClass", and an anonymous object (MyClass.prototype) which holds the methods you provided.

提交回复
热议问题