Javascript OOP recommendations?

I'm tired of seeing dozens of different ways to do object oriented programming in Javascript. Can someone just tell me which technique I should use, given that I want to work on a large-scale project, and I want my code to be future proof?

+10
javascript oop
Sep 20 '10 at 9:23
source share
9 answers

These are just a few quick recommendations that I came up with, if anyone else makes sense to add, I installed this answer as a community wiki, so it will be easy enough for you to edit.

  1. The namespace of objects so that they never conflict with third-party JavaScript libraries.
      window ['Andrew'] ['JS'] = {
         addEvent: function (el, evName) {/ * Stuff * /},
         Rectangle: function (width, height) {/ * Stuff * /}
     }; 
    So you should create a rectangle object using:
      var myRect = new Andrew.JS.Rectangle (14,11); 
    And then your code will never interfere, or someone else Rectangle will interfere with it.

  2. Use a consistent naming strategy, in particular:
    • Names of objects must be uppercase, everything else (variables, functions) must begin with a lowercase character, i.e.
        var myRect = new Andrew.JS.Rectangle (14,11);
       document.write (myRect.getArea ()); 
    • Make sure everything makes sense, i.e. verbs for methods, nouns + adjectives for parameters.

  3. Ensure that all relevant methods and parameters relate to the object to which they belong. for example, In this example, the rectangle area can be converted to square feet using the inSquareFeet() method.

      myRect.getAreaObject (). inSquareFeet (); 
    Make sure that inSquareFeet is the method of the object returned by getAreaObject() , and not the Andrew.JS.Rectangle method

  4. Use constructors or, more specifically, try as much as possible to make sure that the object does not need further initialization, which will be used after its creation, but instead:
      var Person = function ()
     {
         this.name = "";
         this.sayHello = function ()
         {
             alert (this.name + "says 'Hello!'");
             return this;
         }
     }
    
     var bob = new Person ();
     bob.name = "Bob Poulton";
     bob.sayHello (); 
    try:
      var Person = function (name)
     {
         this.name = name;
         this.sayHello = function ()
         {
             alert (this.name + "says 'Hello!'");
             return this;
         }
     }
    
     var bob = new Person ("Bob Poulton");
     bob.sayHello (); 
+9
Sep 20 '10 at 9:36
source share

I always use John resig:

http://ejohn.org/blog/simple-javascript-inheritance/

It is simple and does not require any frameworks to work.

+7
Sep 20 2018-10-12T00:
source share

Since you are working on a large-scale project, I would suggest a javascript framework like mootools http://mootools.net/ for example.

It has a good class and inheritance structure.

+1
Sep 20 '10 at 9:40
source share

for your information only, I think YUI provides some excellent guides on this topic

+1
Sep 20 '10 at
source share
 //Create and define Global NameSpace Object ( function(GlobalObject, $, undefined) { GlobalObject.Method = function() { ///<summary></summary> } GlobalObject.Functionality = {}; }) (GlobalObject = GlobalObject || {}, jQuery); //New object for specific functionality ( function(Events, $, undefined) { //Member Variables var Variable; // (Used for) , (type) // Initialize Events.Init = function() { ///<summary></summary> } // public method Events.PublicMethod = function(oParam) { ///<summary></summary> ///<param type=""></param> } // protected method (typically define in global object, but can be made available from here) GlobalObject.Functionality.ProtectedMethod = function() { ///<summary></summary> } // internal method (typically define in global object, but can be made available from here) GlobalObject.InternalMethod = function() { ///<summary></summary> } // private method var privateMethod = function() { ///<summary></summary> } }) (GlobalObject.Funcitonality.Events = GlobalObject.Funcitonality.Events || {}, jQuery ) // Reusable "class" object var oMultiInstanceClass = function() { // Memeber Variables again var oMember = null; // // Public method this.Init = function(oParam) { oMember = oParam; for ( n = 1; i < oMemeber.length; i += 1 ) { new this.SubClass.Init(oMember[i]); // you get the point, yeah? } } this.Subclass = function() { this.Init = function() { } } } 

The strength of this is that it automatically initializes the Global object, allows you to maintain the integrity of your code and organize each functionality in a specific group according to your definition.

This structure is solid, presenting all the basic syntax things you would expect from OOP without keywords.

There are even some ingenious ways to configure interfaces. If you decide to go this far, a simple search will give you some useful tips and tricks.

Even intellisense customization is possible with javascript and visual studio, and then defining each part and referencing them makes javascript more clean and manageable.

Using these three methods as necessary in your situation helps keep the global namespace clean, keep your code organized and maintain separation of problems for each object .. if used correctly. Remember that an object-oriented design is useless if you do not use the logic of using objects!

+1
Oct. 25 '12 at 17:33
source share

I use such a template and recommend you use it:

 function Person(firstname, lastname, age) { var self = this; var _ = {}; // Private members. var firstname = firstname; var lastname = lastname; var age = age || 'unknown'; // Private methods. function first_letter_to_uppercase(str) { return str.charAt(0).toUpperCase() + str.substr(1); } // Public members and methods. _.get_age = function() { return age; } _.get_name = function() { return first_letter_to_uppercase(firstname) + ' ' + first_letter_to_uppercase(lastname); } return _; } var p = new Person('vasya', 'pupkin', 23); alert("It " + p.get_name() + ', he is ' + p.get_age() + ' years old.') 
0
Sep 20 '10 at 10:10
source share

My ideal OOP object is similar to the Instance method with prototypes:

Example:

 var Users = function() { var _instance; this.prototype.getUsername = function(){/*...*/} this.prototype.getFirstname = function(){/*...*/} this.prototype.getSecurityHash = function(){/*...*/} /*...*/ /*Static Methods as such*/ return { /*Return a small Object*/ GetInstance : function() { if(_instance == null) { _instnance = new Users(arguments); } return _instnance; //Return the object }, New: function() { _instnance = null; //unset It return this.GetInstnace(arguments); } } } 

Then I will always use as:

 Firstname = Users.GetInstance('Robert','Pitt').getFirstname(); Username = Users.GetInstance().getUsername(); //Returns the above object. Me = Users.New('Robert',null); //Deletes the above object and creates a new instance. Father = Users.New('Peter','Piper'); //New Object Me.AddFather(Father); //Me Object. 

And this is the way I go down when it comes to building the JavaScript OO Style architecture.

0
Sep 20 '10 at 10:22
source share
 function foo() { var bar = function() { console.log("i'm a private method"); return 1; }; var iAmAPrivateVariable = 1; return { publicMethod: function() { alert(iAmAPrivateVariable); }, publicVariable: bar() } } //usage var thing = foo() 

This is a functional approach and much more suitable for it (for example, encapsulation), and then everything that you see

In general, you should not do OO in javascript, it is not such a big language for it for many reasons. Think of a diagram with short-angle brackets and half-columns, and you will start writing a language like professionals. In this case, once OO is better suited. In such cases the above is usually the best choice.

to bring inheritance to the mix

 function parent() { return { parentVariable: 2 }; } function foo() { var bar = function() { console.log("i'm a private method"); return 1; }; var iAmAPrivateVariable = 1; me = parent(); me.publicMethod = function() { alert(iAmAPrivateVariable); }; me.publicVariable = bar(); return me; } 

This makes things a little more complicated, but achieves the desired end result, but at the same time uses a functional approach to OO concepts (in this case, using decorator functions instead of real inheritance). What I like about the whole approach is that we continue to view objects as they are intended to be in that language - a bag of property to which you can attach material as you wish.

One more note: this is wildly different from what you will see most of the time on most tasks that you will ever work on, and it is often very difficult to explain a) what is happening, and b) why it is a good idea for colleagues.

0
Sep 20 '10 at 12:41
source share

You can try with a simple, useful and quick object:

 var foo = { foo1: null, foo2: true, foo3: 24, foo4: new Array(), nameOfFunction1: function(){ alert("foo1"); }, nameOfFunction2: function(){ alert("foo2"); }, } 

To use this, you need to instantiate this object and use it as an object in java:

 foo.nameOfFunction2(); 

You can also check this link for another solution: http://www.javascriptkit.com/javatutors/oopjs.shtml

I hope the answer to your question.

-2
Sep 20 2018-10-09T00:
source share



All Articles