In general, the implementation of a pure OOP approach on js, up to the es6 standard , is one of the most non-trivial tasks and therefore it has many solutions:
Option 1 - find a suitable js library
There are many such libraries on the Internet, here are a couple of examples:
Option 2 - use js compiler
Too many options, for example:
- Babel - compiles (translates) vanilla es6 code.
- TypeScript is a separate js superset positioned as js c types.
Option 3 - write your own implementation
The answers already have the simplest implementation of a class using the module-pattern , but the OOP does not end there, but what about inheritance? In js, the inheritance mechanism via prototype is implemented like this:
MyClass.prototype = Object.create(Base.prototype);
But this will only copy the methods of the prototype, and we still have the properties of the object itself - in OOP these are static methods and properties, so I use the following pattern:
function extend(current, base) { // копируем статические проперти for (var key in base) { if (base.hasOwnProperty(key)) { current[key] = base[key]; } } // копируем прототип current.prototype = Object.create(base.prototype); };
Now you can use it:
var Dialogs; (function (Dialogs) { // класс Popup Dialogs.Popup = (function () { // статическая функция Popup.show = function () { alert("show"); }; // Конструктор класса function Popup(message) { this._message = message; } Popup.prototype.hello = function () { var self = this; var message = $(this._message).click(function () { self.sayBye(); }); $("#container").append(message); }; Popup.prototype.sayBye = function () { alert("Bye"); }; Popup.prototype.say = function () { alert(this._message); }; return Popup; }()); // класс Popup2 extend Popup Dialogs.Popup2 = (function (superClass) { // наследуем прототип extend(Popup2, superClass); function Popup2() { // вызываем конструктор базового класса superClass.apply(this, arguments); } // перегружаем базовую функцию sayBye Popup2.prototype.sayBye = function () { alert("Bye2"); }; return Popup2; }(Dialogs.Popup)); // передаем базовый класс })(Dialogs || (Dialogs = {}));
In your code, you create a scope (namespace) of Dialogs within which all the magic happens, and you can also declare global variables in it:
var Dialogs; (function (Dialogs) { var a = 100; // переменная видна внутри Dialogs Dialogs.b = 100; // можно обратиться как к Dialogs.b снаружи ...
You can of course without it, then the class pattern will look like this:
var Popup2 = (function (superClass) { extend(Popup2, superClass); function Popup2() { superClass.apply(this, arguments); } return Popup2; }(Popup));
see how it works here: jsfiddle
element.find("a.close").click(see the lineelement.find("a.close").click(- Codd Wrench