Javascript - Is It Good Practice?

In our company, we are starting a new web project, I am new to the company, and there are previous applications where the finished document is done just like that. (We're using jQuery by the way)

var AccountingMovements = function AccountingMovements() {

    //sometimes they use var _that = this;
    var _this = this;

    _this.Constructor = function Constructor() {
        //here goes the code when document is ready
    }
}

var $AccountingMovements = new AccountingMovements();
$(document).ready($AccountingMovements.Constructor);

      

When I ask my colleagues why they use this pattern, they tell me that Javascript code should have its own constructor, and this code should be written that way, and when I ask if this is a company rule, they say that it is not, there is not a single company standard that states that it should be written that way. They seem to just do it this way because "This is how it has always been done" instead of saying that this is normal javascript practice or something.

For my part, I learned how to use IIFE with a ready-made jquery doc, which I found in many web examples provided by javascript gurus, an actual usage explanation, and even a Wikipedia article. I am writing my code this way

(function (code) {
    code(window.jQuery, window, document);
}(function ($, window, document) {
    $(function () {
        //here goes the code when document is ready
    });
}));

      

My development leader (who doesn't know too much about javascript because it comes from a background for desktop development, but is good when it comes to business logic) told me that this is a new project when I see a new solution. the best implementation of something or something useful for the job, I shouldn't hesitate to tell him and he will discuss it with other leaders. So I told him about my approach and that I didn't understand the purpose of the old constructor code and that no one gave me a convincing explanation, he told me to go up one-on-one if there is anything that supports this approach considering that I showed him the resources that make the reserve mine to tell the orders in case mine is better, discarding the other method.

So, after all this story, my question is:

Does the javascript constructor have a name? I mean, is this a real standard, practice, or recommendation? Because I couldn't find any information about it. Maybe I am wrong and the constructor approach is better or right, but since I have no information on this, I have to be sure to discuss my implementation.

Thanks in advance.

+3


source to share


4 answers


JavaScript has no special meaning for a word Constructor

; only those meanings that your colleagues ascribed to him. Some JS frameworks, such as dojo, create similarly named functions, but also have specialized, centralized ways of defining objects and centralized places that they call a specified constructor function (instead of manually calling it on the very next line, leaving room for errors )

It is also possible to be misleading into thinking that any JavaScript objects must wait for the DOM to be ready before building themselves. Do you think jQuery creates itself? (And it must be very early before people write $().ready

to make their onload function)



I am not aware of any particular problem with the way your colleagues write their objects, as long as they assign a completely different semantic meaning to their current function Constructor

. The following code, for example var _this = this

, is a constructor. The content of the is-Constructor function is best described onDOM

or similar. If they choose to follow this system, it would be better if their class system goes through a central library; be it your own or someone else's.

+2


source


One big difference is global pollution. Since they don't seem to wrap their functions in an IIFE, all functions and variables will be accessible from the global scope. This can lead to bugs and security issues if third party JS libraries (or even some other internal code) reuse any of them.

The approach you mentioned is very useful as it allows for both defining your code and specifying which part should wait for the DOM:

// IIFE to create a closure to prevent global scope pollution
(function(code) {
  // execute `main` function with params
  code(window.jQuery, window, document);
}(function main($, window, document) {
  $(function readyDOM() {
    //here goes the code when document is ready
  });

  // This is the rest of your code that is not dependent on the DOM
  // Such as any object (constructers) declarations
}));

      

However, this is functionally equivalent to:



// IIFE to create a closure to prevent global scope pollution
(function main($, window, document) {
  $(function readyDOM() {
    //here goes the code when document is ready
  });

  // This is the rest of your code that is not dependent on the DOM
  // Such as any object (constructers) declarations
})(window.jQuery, window, document);

      

Any of these patterns can be used as a wrapper for their object declarations. So, combining this with an object declaration:

// IIFE to create a closure to prevent global scope pollution
(function main($, window, document) {
  $(function readyDOM() {
    $AccountingMovements.Constructor();
  });

  // A better pattern for object constructors
  // Assigning properties directly to `this` in the object constructor
  //  makes them enumerable by default. See http://jsbin.com/kuxuyataci/edit?js,console
  function AccountingMovements() {
    //sometimes they use var _that = this;
    var _this = this;
  }
  AccountingMovements.prototype.Constructor = function Constructor() {
    //here goes the code when document is ready
  };

  // var will be hoisted
  var $AccountingMovements = new AccountingMovements();
})(window.jQuery, window, document);

      

0


source


What they want to achieve is with an application "boot buffer" or "launch button", and when the page is ready, calls Constructor

, but a more appropriate name is a method init

or initialize

.

This is the absolute cheeky way to create / structure an application in my opinion. It can also be used as a module starter, etc.

Using _this

as a reference to the main constructor / object / object is good practice, because soon you will get caught in locks and somehow you will need to reference the main module.

Constructor

I assume this is just a placeholder here, you should never name a variable like this. AccountingMovementsConstructor

this is much better.

What you pasted in here is not really a template, but just an initialization method inside a module.

Google for Javascript design patterns

and more about them.

And keep in mind that letting someone build a large-scale javascript application with Java or other different languages ​​is just an experience: worst idea ever.

Alternatively to the above code:

// Define your module

(function(w) {
    w.namespace.myModule = {
        init: function() {
            console.log('hey, Im ready to rock');
        },

        // Usually you have one of these also
        destroy: function() {
            console.log('good bye world...');
        }
    }
}(window));

// Fast alternative to $(document).ready(...)
$(function() {
    window.namespace.myModule.init(); // hey, Im ready to rock
});

      

You can enable Factory function

to separate public and private variables. But I won't be here right here, this is what you can do with google: P

0


source


Perhaps you misunderstood each other.

The snippet discarded is, for the most part, the JS way of declaring a class . Of course, with the sole purpose of executing a bunch of code in an event, ready

this is overkill. But the project is growing and you need to structure it. This is one of many ways to do it, none of which is the best. This is familiar to programmers coming from pure OOP languages ​​like Java that encourage (or even provide) an object-oriented architecture.

Since JavaScript does not have a built-in syntax for declaring a class (implementation, at least ES2015), several approaches have appeared for this. Everything I've seen has to do with declaring a constructor function. Yours is no exception: while I would say it's not perfect, the constructor code is just fine in the constructor function itself that represents the class. I don't understand why you would like to divide the construction process into two different stages: when the designer has completed his work, the object must be ready for use, a separate construction stage is an unnecessary complication.

For example, here CoffeeScript (roughly a syntax layer on top of JS) does the following:

# CoffeeScript
class Hi
  # A typical method
  # CS is indenetation-sensitive: class contents and
  # function implementations are indented one more level
  # -> denotes a function
  method: ->
    @a += 1

  # `constructor` is a special identifier in CS
  # code from that function goes into an unusual place
  constructor: ->
    @a = 5

      

Here's the output:

// Generated JavaScript
// Entire program is wrapped in IIFE, for isolation.
// Not relevant to the question, but since it in the output
// I want to clarify why it in there.
(function() {
  var Hi;

  Hi = (function() {
    Hi.prototype.method = function() {
      return this.a += 1;
    };

    function Hi() {
      this.a = 5;
    }

    return Hi;

  })();

}).call(this);

      

0


source







All Articles