SoFunction
Updated on 2025-04-13

Mock code for javascript classes and namespaces

Let's start with the easiest paragraph:
Copy the codeThe code is as follows:

// The following lines of code show the simulation definition and use of namespaces, classes, and functions:
NameSpace = {};
= function(){
= function(info){alert(info);}
};
new ().Method("Hello world");

Let's get some visible codes for various situations
1. Class simulation
Copy the codeThe code is as follows:

// Class definition
function Class(info){
// Private members
var privateData = "private data";
var privateMethod = function(){writeline("private");};
function privateMethod2(info){writeline("private");}
// Public members (using this)
= "public data";
= function(){writeline(info);};
};
// Static member of the class
= "static data";
= function(info){writeline(info);};


2. Namespace simulation
Copy the codeThe code is as follows:

function NameSpace(){}
or
NameSpace = {};
or
NameSpace = new Object();

3. Objective: Create a class instance and call the instance method
Copy the codeThe code is as follows:

var o = new ("hello world");
();
// Use the existing class definition and hang it under NameSpace with a static method
NameSpace.Class1 = Class;
new NameSpace.Class1("new NameSpace.Class1().Method()").Method();
// Or: Create a new class definition
NameSpace.Class2 = function(info){
= function(){writeline(info);};
};
new NameSpace.Class2("new NameSpace.Class2().Method()").Method();


4. Target: Call the static function of the class
Copy the codeThe code is as follows:

();
// Static object + static method
NameSpace.Class3 = {}; // {} means that this is an object, or use new object();
NameSpace. = function(info) {writeline(info);};
NameSpace.("NameSpace.()");
// Or: new object to static members
NameSpace.Class4 = new Class("NameSpace.()");
NameSpace.();
// Or: anonymous functions are used to define classes, and then use new to create objects
NameSpace.Class5 = new (function(info){
= function(){writeline(info);};
})("NameSpace.()");
NameSpace.();
// Or: JSON method (class definition + creation is completed at the same time)
// The advantage is that it is simple, but the disadvantage is that it cannot pass parameters into it.
NameSpace.Class6 = {
Method : function(info){writeline(info);}
};
NameSpace.("NameSpace.()");

Demo code:

[Ctrl+A Select all Note:Introducing external Js requires refreshing the page before execution]

PS. I am very happy, vs2010's intelligent perception of js is getting better and better: p
Source: