search
HomeBackend DevelopmentPHP Tutorial5 ways to create a namespace in JavaScript_PHP Tutorial

Global variables in JavaScript often cause naming conflicts, and sometimes even rewriting variables is not in the order you imagine. You can take a look at the following example:

Copy code The code is as follows:

var sayHello = function() {
return 'Hello var';
};

function sayHello(name) {
Return 'Hello function';
};

sayHello();


The final output is
Copy code The code is as follows:

> "Hello var"

Why is this? According to StackOverFlow's explanation, JavaScript is actually parsed in the following order.
Copy code The code is as follows:

function sayHello(name) {
Return 'Hello function';
};

var sayHello = function() {
Return 'Hello var';
};

sayHello();


Function declarations without var are parsed in advance, so modern JS writing recommends that you always use prefixed var to declare all variables;

The best way to avoid global variable name conflicts is to create a namespace. Here are several common ways to create namespaces in JS.

1. Create via function

This is a relatively common way of writing. It is implemented by declaring a function, setting initial variables in the function, and writing public methods into the prototype, such as:

Copy code The code is as follows:

var NameSpace = NameSpace || {};
/*
Function
*/
NameSpace.Hello = function() {
this.name = 'world';
};
NameSpace.Hello.prototype.sayHello = function(_name) {
Return 'Hello ' + (_name || this.name);
};
var hello = new NameSpace.Hello();
hello.sayHello();

This way of writing is verbose and not conducive to code compression (jQuery uses fn instead of prototype), and it needs to be instantiated (new) before calling. Using Object to write it in JSON format can make it more compact:

2. Create Object through JSON object

Copy code The code is as follows:

/*
Object
*/
var NameSpace = NameSpace || {};
NameSpace.Hello = {
Name: 'world'
, sayHello: function(_name) {
Return 'Hello ' + (_name || this.name);
}
};

Call
Copy code The code is as follows:

NameSpace.Hello.sayHello('JS');
> Hello JS;

This way of writing is relatively compact. The disadvantage is that all variables must be declared as public, so all references to these variables need to be added with this to indicate the scope, and the writing method is also slightly redundant.

3. Implementation through Closure and Object

Declare all variables and methods in the closure, and return the public interface through a JSON Object:

Copy code The code is as follows:

var NameSpace = NameSpace || {};
NameSpace.Hello = (function() {
//Public object to be returned
var self = {};
//Private variables or methods
var name = 'world';
//Public methods or variables
self.sayHello = function(_name) {
Return 'Hello ' + (_name || name);
};
//Returned public object
return self;
}());

4. Improved writing methods of Object and closure

In the previous example, the internal call to the public method also needs to add self, such as: self.sayHello(); Here you can finally return the JSON objects of all public interfaces (methods/variables).

Copy code The code is as follows:

var NameSpace = NameSpace || {};
NameSpace.Hello = (function() {
var name = 'world';
var sayHello = function(_name) {
Return 'Hello ' + (_name || name);
};
Return {
SayHello: sayHello
};
}());

5. Concise writing of Function

This is a relatively simple implementation with a compact structure. It uses function instances and does not require instantiation (new) when calling. The solution comes from stackoverflow:

Copy code The code is as follows:

var NameSpace = NameSpace || {};
NameSpace.Hello = new function() {
var self = this;
var name = 'world';
self.sayHello = function(_name) {
Return 'Hello ' + (_name || name);
};
};

Additions are welcome.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824824.htmlTechArticleGlobal variables in JavaScript often cause naming conflicts, and sometimes even rewriting variables is not what you imagine. In order, you can take a look at the following example: Copy the code code as...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.