How to create your own namespace or class in javascript

I want to create my own namespace like $ for jQuery

 (function(app) {
     app.fn.log = function(data) {
          console.log(data);
        };
 }(app));

 app.log("data");

But this code returns an error - Unprepared ReferenceError: application not defined

How to create your own namespace?

+4
source share
3 answers
window.app = {};

(function(app) {
    app.log = function(data) {
         console.log(data);
       };
}(app));

app.log("data");

jQuery is slightly different from it fn: since you use the syntax $('selector')to find elements that need to be processed, jQuery returns a spetial wrapper containing all-like fn.funcdefinitions that you made in addition to the built-in functions.

, - , . :

window.app = function(p) {

    // do whatever you need

    var wrapper = {
        // standard common fields
    };

    if (app.fn) {
        // extend wrapper with app.fn
    }

    return wrapper;
};

, ?

, , , app , .

+2

javascript ( ). , , $ :

//Global script declaration
var NAMESPACE = {};

//Check if you need to initialize your namespace
NAMESPACE.FooSpace = NAMESPACE.FooSpace || {};

//Some other script
NAMESPACE.FooSpace = (function($) {
    function Foo1() {
    }

    function Foo2() {
        return $.getSomething(); //some existing function inside of someObjectWithANonConflictingName object
    }    

    return { Foo1: Foo1, Foo2: Foo2 };
})(someObjectWithANonConflictingName);

//somewhere else in code (call as a constructor function)
var foo = new NAMESPACE.FooSpace.Foo1();
//somewhere else in code (call as regular function)
var foo2 = Foo2();
  • , NAMESPACE, .
  • , , .
  • , , NAMESPACE.
  • - ( ).
+3

, app. IIFE, ! jQuery , IIFE jQuery :

(function(app) {
     app.fn.log = function(data) {
          console.log(data);
        };
 }($)); // where $ is your jQuery.

$.log("data");

! IIFE!

+1
source

Source: https://habr.com/ru/post/1529158/


All Articles