Geen categorieën toegewezen

Object-oriented Programming with JavaScript

Versie door Mlink-rodrigue (overleg | bijdragen) op 5 sep 2019 om 09:32
(wijz) ← Oudere versie | Huidige versie (wijz) | Nieuwere versie → (wijz)

A sample text to demonstrate syntax representation and syntax editing in the Visual Editor.

Namespace

A namespace is a container in which developers can combine functionalities under a unique, application-specific name. In JavaScript, a namespace is a common object that contains methods, properties, and objects.


hint icon
Unlike some other object-oriented programming languages, there is no difference in the JavaScript language level between a regular object and a namespace.

The idea behind creating a namespace in JavaScript is simple: create a global object that has all variables, methods, and functions as properties. In addition, the use of namespaces can prevent naming conflicts in the application.

To create a global object called MYAPP:

1 // global namespace
2 var MYAPP = MYAPP || {};


The above code first checks if MYAPP has already been defined (either in the same or a different file). If MYAPP has already been defined then the global object MYAPP will be used. Otherwise, an empty object called MYAPP is created, which later can encapsulate methods, functions, variables and other objects.

Within a namespace, additional namespaces can be created:

1 // sub namespace
2 MYAPP.event = {};


The following code creates a namespace and adds variables, functions, and methods to it:


 1 // Create container called MYAPP.commonMethod for common method and properties
 2 MYAPP.commonMethod = {
 3   regExForName: "", // define regex for name validation
 4   regExForPhone: "", // define regex for phone no validation
 5   validateName: function(name){
 6     // Do something with name, you can access regExForName variable
 7     // using "this.regExForName"
 8   },
 9  
10   validatePhoneNo: function(phoneNo){
11     // do something with phone number
12   }
13 }
14 
15 // Object together with the method declarations
16 MYAPP.event = {
17     addListener: function(el, type, fn) {
18     //  code stuff
19     },
20    removeListener: function(el, type, fn) {
21     // code stuff
22    },
23    getEvent: function(e) {
24    // code stuff
25    }
26   
27    // Can add another method and properties
28 }
29 
30 //Syntax for Using addListner method:
31 MYAPP.event.addListener("yourel", "type", callback);


Source for this sample text: https://developer.mozilla.org/de/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript

Bijlagen

Overleg