Home  >  Article  >  Web Front-end  >  js object-oriented technology to create advanced web applications_js object-oriented

js object-oriented technology to create advanced web applications_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:33:53917browse

JavaScript Objects are Dictionaries
In C or C#, when talking about objects, we mean instances of a class or structure. Objects have different properties and methods depending on the template (i.e. class) in which they are instantiated. This is not the case with JavaScript objects. In JavaScript, an object is just a set of name/value pairs; that is, think of a JavaScript object as a dictionary containing string keys. We can use the familiar "." (dot) operator or the "[]" operator to get and set the properties of an object, which is the usual approach when working with dictionaries. The following code snippet

Copy code The code is as follows:

var userObject = new Object();
userObject.lastLoginTime = new Date();
alert(userObject.lastLoginTime);

functions exactly the same as the following code snippet:
Copy code The code is as follows:

var userObject = {}; // equivalent to new Object()
userObject["lastLoginTime" ] = new Date();
alert(userObject[“lastLoginTime”]);

We can also define the lastLoginTime property directly in the definition of userObject, as shown below:
Copy code The code is as follows:

var userObject = { “lastLoginTime”: new Date() };
alert(userObject.lastLoginTime);

Note that it is very similar to the C# 3.0 object initializer. Also, those familiar with Python will notice that instantiating userObject in the second and third snippets is exactly the same as specifying a dictionary in Python. The only difference is that JavaScript objects/dictionaries only accept string keys, rather than hashable objects like Python dictionaries.
These examples also show that JavaScript objects are more malleable than C or C# objects. You do not have to declare the property lastLoginTime beforehand — if userObject does not have a property by that name, the property will be added directly to userObject. This won't be surprising if you remember that JavaScript objects are dictionaries; after all, we are adding new keywords (and their respective values) to dictionaries all the time.
In this way, we have object properties. What about object methods? Likewise, JavaScript is different from C/C#. To understand object methods, you first need to take a closer look at JavaScript functions.
JavaScript functions are the best
In many programming languages, functions and objects are often considered two different things. In JavaScript, the distinction is blurry—a JavaScript function is actually an object with executable code associated with it. Please think of ordinary functions like this:
Copy code The code is as follows:

function func(x) {
alert(x);
}
func(“blah”);

This is how functions are usually defined in JavaScript. However, the function can also be defined as follows, where you create an anonymous function object and assign it to the variable func
Copy code The code is as follows:

var func = function(x) {
alert(x);
};
func(“blah2”);

You can even use the Function constructor like this:
Copy the code The code is as follows:

var func = new Function(“x”, “alert(x);”);
func(“blah3”);

This example shows that the function actually just supports The object that the function call operates on. The last way to define a function using the Function constructor is not commonly used, but the possibilities it presents are very interesting, because you may notice that the body of the function is exactly the String parameter of the Function constructor. This means that you can construct arbitrary functions at runtime.
To further demonstrate that functions are objects, you can set or add properties to functions just like any other JavaScript object:
Copy codeThe code is as follows:

function sayHi(x) {
alert(“Hi, “ x “!”);
}
sayHi.text = “Hello World!”;
sayHi[“ text2”] = “Hello World... again.”;
alert(sayHi[“text”]); // displays “Hello World!”
alert(sayHi.text2); // displays “Hello World... again.”

As objects, functions can also be assigned to variables, passed as parameters to other functions, returned as values ​​of other functions, and can be used as attributes of objects or elements of arrays for storage and so on. Figure 1 provides such an example.
Functions in JavaScript are the best
Copy code The code is as follows:

/ / assign an anonymous function to a variable
var greet = function(x) {
alert(“Hello, “ x);
};
greet(“MSDN readers”);
// passing a function as an argument to another
function square(x) {
return x * x;
}
function operateOn(num, func) {
return func(num) ;
}
// displays 256
alert(operateOn(16, square));
// functions as return values ​​
function makeIncrementer() {
return function(x) { return x 1; };
}
var inc = makeIncrementer();
// displays 8
alert(inc(7));
// functions stored as array elements
var arr = [];
arr[0] = function(x) { return x * x; };
arr[1] = arr[0](2);
arr[2 ] = arr[0](arr[1]);
arr[3] = arr[0](arr[2]);
// displays 256
alert(arr[3]);
// functions as object properties
var obj = { “toString” : function() { return “This is an object.”; } };
// calls obj.toString()
alert(obj);

With this in mind, adding a method to an object will be easy: just choose the name and assign the function to that name. Therefore, I defined three methods in the object by assigning anonymous functions to the corresponding method names:
Code
Copy Code The code is as follows:

var myDog = {
“name” : “Spot”,
“bark” : function() { alert(“Woof!”); },
"displayFullName" : function() {
alert(this.name "The Alpha Dog");
},
"chaseMrPostman" : function() {
// implementation beyond the scope of this article
}
};
myDog.displayFullName();
myDog.bark(); // Woof!

C /C# development You should be familiar with the "this" keyword used in the displayFullName function - it refers to an object through which methods are called (developers using Visual Basic should also be familiar with it, where it is called "Me"). So in the example above, the value of "this" in displayFullName is the myDog object. However, the value of "this" is not static. When "this" is called from a different object, its value changes to point to the corresponding object, as shown in Figure 2.
"this" changes as the object changes
Copy code The code is as follows:

function displayQuote() {
// the value of “this” will change; depends on
// which object it is called through
alert(this.memorableQuote);
}
var williamShakespeare = {
"memorableQuote": "It is a wise father that knows his own child.",
"sayIt" : displayQuote
};
var markTwain = {
"memorableQuote": "Golf is a good walk spoiled.",
"sayIt" : displayQuote
};
var oscarWilde = {
"memorableQuote": "True friends stab you in the front."
// we can call the function displayQuote
// as a method of oscarWilde without assigning it
// as oscarWilde's method.
//"sayIt" : displayQuote
};
williamShakespeare. sayIt(); // true, true
markTwain.sayIt(); // he didn't know where to play golf
// watch this, each function has a method call()
// that allows the function to be called as a
// method of the object passed to call() as an
// argument.
// this line below is equivalent to assigning
// displayQuote to sayIt, and calling oscarWilde.sayIt().
displayQuote.call(oscarWilde); // ouch!

The last line in Figure 2 represents another way of calling a function as a method of an object. Remember, functions in JavaScript are objects. Every function object has a method called call that calls a function as the first argument. That is, any object passed to call as the first parameter of the function will become the value of "this" in the function call. This technique is useful for calling base class constructors, which will be covered later.
One thing to remember is never to call a function that contains "this" (but does not own an object). Otherwise, you will violate the global namespace because in this call, "this" will refer to the global object, which will inevitably lead to disaster for your application. For example, the following script changes the behavior of JavaScript's global function isNaN. Don't do this!
Code
Copy code The code is as follows:

alert("NaN is NaN: " isNaN(NaN));
function x() {
this.isNaN = function() {
return “not anymore!”;
};
}
// alert !!! trampling the Global object!!!
x();
alert(“NaN is NaN: “ isNaN(NaN));

So far, we have introduced How to create an object, including its properties and methods. But if you pay attention to all the code snippets above, you'll see that the properties and methods are hardcoded in the object definition itself. But what if you need more control over object creation? For example, you might need to calculate an object's property values ​​based on certain parameters. Alternatively, you may need to initialize an object's properties to values ​​that are only available at runtime. It may also be necessary to create multiple instances of an object (this requirement is very common).
In C#, we use classes to instantiate object instances. But JavaScript is different because it doesn't have classes. As you'll see in the next section, you can take advantage of this situation: a function acts as a constructor when used with the "new" operator.
Constructors instead of classes
As mentioned earlier, the strangest thing about JavaScript OOP is that JavaScript, unlike C# or C, does not have classes. In C#, when you do something like:
Dog spot = new Dog();
will return an object that is an instance of the Dog class. But in JavaScript, there are no classes. The closest approach to accessing a class is to define a constructor as follows:
Code
Copy code The code is as follows:

function DogConstructor(name) {
this.name = name;
this.respondTo = function(name) {
if(this.name == name) {
alert(“Woof”);
}
};
}
var spot = new DogConstructor(“Spot”);
spot.respondTo(“Rover”); // nope
spot.respondTo(“Spot”); // yeah!

So, what will be the result? Ignore the DogConstructor function definition for now and take a look at this line:
var spot = new DogConstructor("Spot");
The operation performed by the "new" operator is simple. First, it creates a new empty object. The function call immediately following it is then executed, setting the new empty object to the value of "this" in that function. In other words, the above line of code containing the "new" operator can be considered to be equivalent to the following two lines of code:
Copy code The code is as follows:

// create an empty object
var spot = {};
// call the function as a method of the empty object
DogConstructor.call (spot, "Spot");

As seen in the DogConstructor body, calling this function will initialize the object and the keyword "this" will refer to this object during the call. This way, you can create templates for your objects! Whenever you need to create a similar object, you can call "new" with the constructor and the returned result will be a fully initialized object. This is very similar to classes, isn't it? In fact, the name of the constructor in JavaScript is usually the name of the class being simulated, so in the above example, the constructor Dog can be named directly:
Code
Copy code The code is as follows:

// Think of this as class Dog
function Dog(name) {
// instance variable
this.name = name;
// instance method? Hmmm...
this.respondTo = function(name) {
if(this.name == name) {
alert( "Woof");
}
};
}
var spot = new Dog("Spot");

In the Dog definition above, I defined an instance variable named name. Each object created with Dog as its constructor has its own copy of the instance variable name (which, as mentioned earlier, is the object dictionary entry). This is the desired outcome. After all, each object needs its own copy of instance variables to represent its state. But if you look at the next line, you'll see that each Dog instance also has its own copy of the respondTo method, which is a waste; you only need one respondTo instance that can be shared among Dog instances! This problem can be avoided by defining respondTo outside of Dog, as follows:
Copy code The code is as follows:

function respondTo() {
// respondTo definition
}
function Dog(name) {
this.name = name;
// attached this function as a method of the object
this.respondTo = respondTo;
}

In this way, all Dog instances (that is, all instances created with the constructor Dog) can share an instance of the respondTo method. But as the number of methods increases, maintenance becomes increasingly difficult. Finally, there will be a lot of global functions in the code base, and things will only get worse as you add more "classes" (especially if their methods have similar names). But this problem can be solved better using prototype objects, which is the subject of the next section.
Prototype
In object-oriented programming using JavaScript, the prototype object is a core concept. The name comes from the concept that objects in JavaScript are created as copies of existing instance (i.e. prototype) objects. Any properties and methods of this prototype object will appear as properties and methods of the object created from the prototype's constructor. We can say that these objects inherit properties and methods from their prototype. When you create a new Dog object like this:
var buddy = new Dog("Buddy"); The object referenced by
buddy will inherit properties and methods from its prototype, although this is only possible from this line It's impossible to tell for sure where the prototype came from. The prototype of the object buddy comes from the properties of the constructor (in this case the function Dog).
In JavaScript, every function has a property called "prototype" that is used to refer to the prototype object. This prototype object in turn has a property called "constructor" which in turn refers to the function itself. This is a circular reference, and Figure 3 better illustrates this circular relationship.

Figure 3 The prototype of each function has a Constructor attribute
Now when you create an object with a function (Dog in the example above) via the "new" operator, the resulting object will inherit the properties of Dog.prototype. In Figure 3 you can see that the Dog.prototype object has a constructor property that refers back to the Dog function. This way, every Dog object (inherited from Dog.prototype) has a constructor property that refers back to the Dog function. The code in Figure 4 confirms this. Figure 5 shows this relationship between constructors, prototype objects, and objects created with them.
Copy code The code is as follows:

var spot = new Dog("Spot");
// Dog.prototype is the prototype of spot
alert(Dog.prototype.isPrototypeOf(spot));
// spot inherits the constructor property
// from Dog.prototype
alert (spot.constructor == Dog.prototype.constructor);
alert(spot.constructor == Dog);
// But constructor property doesn't belong
// to spot. The line below displays "false"
alert(spot.hasOwnProperty("constructor"));
// The constructor property belongs to Dog.prototype
// The line below displays "true"
alert(Dog. prototype.hasOwnProperty(“constructor”));


Figure 5 Instance inherits its prototype
Some readers may have noticed the calls to the hasOwnProperty and isPrototypeOf methods in Figure 4. Where did these methods come from? They are not from Dog.prototype. In fact, there are other methods called toString, toLocaleString, and valueOf in Dog.prototype and Dog instances, but none of them come from Dog.prototype. You see, just like System.Object in the .NET Framework serves as the ultimate base class for all classes, Object.prototype in JavaScript is the ultimate base prototype for all prototypes. (The prototype of Object.prototype is null.)
In this example, remember that Dog.prototype is an object. It is created by calling the Object constructor (although it is invisible):
Dog.prototype = new Object();


So, just as Dog instances inherit Dog.prototype, Dog. prototype inherits from Object.prototype. This causes all Dog instances to also inherit the methods and properties of Object.prototype.
Every JavaScript object inherits a prototype chain, and all prototypes terminate at Object.prototype. Note that the inheritance you've seen so far is between active objects. It is different from the common concept of inheritance, which refers to inheritance between classes when they are declared. Therefore, JavaScript inheritance is more dynamic. It achieves this using a simple algorithm as follows: When you try to access a property/method of an object, JavaScript checks whether the property/method is defined in that object. If not, the object's prototype is checked. If not, then the prototype of the object's prototype is checked, and so on, all the way to Object.prototype. Figure 6 illustrates this parsing process.

Figure 6 Parsing the toString() method in the prototype chain (click the image for a larger view)
The way JavaScript dynamically parses property access and method calls produces some special effects:
Changes to the prototype are immediately present on objects that inherit from the prototype object, even after those objects are created.
If property/method X is defined in an object, the property/method with the same name will be hidden in the prototype of the object. For example, you can override the toString method of Object.prototype by defining the toString method in Dog.prototype.
Changes are only propagated in one direction, from the prototype to its derived object, but not in the opposite direction.
Figure 7 illustrates these effects. Figure 7 also shows how to resolve the previously encountered problem of unwanted method instances. By placing methods inside a prototype, you can enable objects to share methods without having to have separate function object instances for each object. In this example, rover and spot share the getBreed method until the toString method is overridden in spot in any way. Thereafter, spot has its own version of the getBreed method, but the rover object and subsequent objects created with the new GreatDane will still share the instance of the getBreed method defined in the GreatDane.prototype object.
Inherit prototype
Copy code The code is as follows:

function GreatDane() { }
var rover = new GreatDane();
var spot = new GreatDane();
GreatDane.prototype.getBreed = function() {
return “Great Dane”;
};
// Works, even though at this point
// rover and spot are already created.
alert(rover.getBreed());
// this hides getBreed() in GreatDane.prototype
spot.getBreed = function() {
return “Little Great Dane”;
};
alert(spot.getBreed());
// but of course , the change to getBreed
// doesn't propagate back to GreatDane.prototype
// and other objects inheriting from it,
// it only happens in the spot object
alert(rover. getBreed());

Static Properties and Methods
Sometimes you need to bind to a property or method of a class rather than an instance, that is, static properties and methods . This is easy to do in JavaScript because functions are objects whose properties and methods can be set as needed. Since constructors represent classes in JavaScript, you can add static methods and properties directly to the class by setting them in the constructor, like this:
Copy Code The code is as follows:

function DateTime() { }
// set static method now()
DateTime.now = function() {
return new Date();
};
alert(DateTime.now());

The syntax for calling static methods in JavaScript is almost identical to that in C#. This shouldn't come as a surprise since the name of the constructor is actually the name of the class. In this way, there are classes, public properties/methods, and static properties/methods. Need anything else? Private members, of course. But JavaScript doesn't natively support private members (and likewise, protected members). Anyone can access all properties and methods of an object. But there are ways to make classes contain private members, but before that, you first need to understand closures.

Closure
I have never consciously learned JavaScript. I had to learn it quickly because I found that without it I was less prepared to write AJAX applications for real work. At first, I felt as if my programming level had dropped several levels. (JavaScript! What would my C friends say?) But once I got over the initial hurdle, I discovered that JavaScript is actually a powerful, expressive, and very concise language. It even has features that other, more popular languages ​​are just starting to support.
One of the more advanced features of JavaScript is its support for closures, a feature that C# 2.0 supports through its anonymous methods. Closures are a runtime phenomenon that occurs when an inner function (or inner anonymous method in C#) is bound to a local variable of its outer function. Obviously, unless this inner function is somehow accessible to the outer function, it doesn't make much sense. An example can better illustrate this point.
Suppose you need to filter a sequence of numbers based on a simple condition. This condition is: only numbers greater than 100 can pass the filter, and the remaining numbers are ignored. To do this, you can write a function like the one in Figure 8.
Filter elements based on predicates
Copy code The code is as follows:

function filter(pred, arr) {
var len = arr.length;
var filtered = []; // shorter version of new Array();
// iterate through every element in the array ...
for(var i = 0; i < len; i ) {
var val = arr[i];
// if the element satisfies the predicate let it through
if (pred(val)) {
filtered.push(val);
}
}
return filtered;
}
var someRandomNumbers = [12, 32, 1, 3, 2, 2, 234, 236, 632,7, 8];
var numbersGreaterThan100 = filter(
function(x) { return (x > 100) ? true : false; },
someRandomNumbers) ;
// displays 234, 236, 632
alert(numbersGreaterThan100);

However, now we want to create different filter conditions, assuming that this time only numbers greater than 300 can pass the filter , you can write the following function:

Copy the code The code is as follows:

var greaterThan300 = filter(
function(x) { return (x > 300) ? true : false; },
someRandomNumbers);

Then, maybe you need to filter greater than 50, 25, 10, 600 and so on, but as a smart person you will find that they all have the same predicate "greater than", only the numbers are different. Therefore, the individual numbers can be separated using a function similar to:
Copy the code The code is as follows:

function makeGreaterThanPredicate(lowerBound) {
return function(numberToCheck) {
return (numberToCheck > lowerBound) ? true : false;
};
}

In this way, You can write the following code:

Code
Copy code The code is as follows:

var greaterThan10 = makeGreaterThanPredicate(10);
var greaterThan100 = makeGreaterThanPredicate(100);
alert(filter(greaterThan10, someRandomNumbers));
alert(filter(greaterThan100, someRandomNumbers));

By observing the inner anonymous function returned by the function makeGreaterThanPredicate, you can find that the anonymous inner function uses lowerBound, which is the parameter passed to makeGreaterThanPredicate. Following the general rules of scoping, when makeGreaterThanPredicate exits, lowerBound goes out of scope! But here, the inner anonymous function still carries lowerBound, even long after makeGreaterThanPredicate exits. This is what we call a closure: because the inner function closes the environment in which it is defined (i.e. the parameters and local variables of the outer function).
You may not feel that closures are very powerful at first. But when applied correctly, they can be a very creative and fun way to help you convert ideas into code. One of the most interesting uses of closures in JavaScript is to simulate private variables of a class.

Simulating private properties
Now let’s look at how closures help simulate private members. Normally, local variables within a function cannot be accessed from outside the function. After the function exits, the local variable disappears forever for various practical reasons. However, if the local variable is captured by the inner function's closure, it will survive. This fact is key to emulating JavaScript private properties. Suppose there is a Person class:
Code
Copy code The code is as follows:

function Person (name, age) {
this.getName = function() { return name; };
this.setName = function(newName) { name = newName; };
this.getAge = function() { return age; };
this.setAge = function(newAge) { age = newAge; };
}

The parameters name and age are local variables of the constructor Person. When Person returns, name and age should disappear forever. However, they are captured by the four internal functions assigned as methods of the Person instance, which effectively leaves name and age to continue to exist, but they can only be accessed strictly through these four methods. So, you can:

Code
Copy the code The code is as follows:

var ray = new Person(“Ray”, 31);
alert(ray.getName());
alert(ray.getAge());
ray.setName(“Younger Ray”);
// Instant rejuvenation!
ray.setAge(22);
alert(ray.getName() “ is now “ ray.getAge()
“ years old.”);

Private members not initialized in the constructor can become local variables of the constructor, as follows:

Code
Copy Code The code is as follows:

function Person(name, age) {
var occupation;
this.getOccupation = function() { return occupation; };
this.setOccupation = function(newOcc) { occupation =
newOcc; };
// accessors for name and age
}

Note that these are private Members are slightly different from the private members we expect from C#. In C#, a class's public methods can access its private members. But in JavaScript, private members can only be accessed through the method that owns them within its closure (since these methods are different from ordinary public methods, they are often called privileged methods). Therefore, in the public method of Person, the private member must still be accessed through the private member's privileged accessor method:
Copy code The code is as follows:

Person.prototype.somePublicMethod = function() {
// doesn't work!
// alert(this.name);
// this one below works
alert(this.getName());
};

Douglas Crockford is famously the first person to discover (or perhaps publish) the technique of using closures to simulate private members. His website, javascript.crockford.com, contains a wealth of information about JavaScript and should be read by any developer interested in JavaScript.

Inheriting from Classes
Up to this point, we have seen how constructors and prototype objects allow you to mock classes in JavaScript. You've seen that the prototype chain ensures that all objects have public methods of Object.prototype, and how closures can be used to simulate private members of a class. But something is missing here. You haven't seen how to derive from a class, which is something you do every day in C#. Unfortunately, inheriting from a class in JavaScript is not as simple as typing a colon to inherit in C#, it requires a lot more work. JavaScript, on the other hand, is very flexible and allows many ways to inherit from classes.
For example, there is a base class Pet, which has a derived class Dog, as shown in Figure 9. How to implement this in JavaScript? The Pet class is easy. You have seen how to implement it:

Copy the code The code is as follows:

// class Pet
function Pet(name) {
this.getName = function() { return name; };
this.setName = function(newName) { name = newName; };
}
Pet.prototype.toString = function() {
return “This pet's name is: “ this.getName();
};
// end of class Pet
var parrotty = new Pet(“Parrotty the Parrot”);
alert(parrotty);

Now, how to create a class Dog derived from Pet? As you can see in Figure 9, Dog has another property, breed, which overrides Pet's toString method (note that JavaScript convention is to use camel casing for method and property names, rather than the Pascal casing recommended in C#). Figure 10 shows how to do this.

Deriving from the Pet class
Copy the code The code is as follows:

// class Dog : Pet
// public Dog(string name, string breed)
function Dog(name, breed) {
// think Dog : base(name)
Pet.call(this, name);
this.getBreed = function() { return breed; };
// Breed doesn't change, obviously! It's read only.
// this.setBreed = function(newBreed) { name = newName; };
}
// this makes Dog.prototype inherits
// from Pet.prototype
Dog.prototype = new Pet();
// remember that Pet .prototype.constructor
// points to Pet. We want our Dog instances'
// constructor to point to Dog.
Dog.prototype.constructor = Dog;
// Now we override Pet .prototype.toString
Dog.prototype.toString = function() {
return “This dog’s name is: “ this.getName()
“, and its breed is: “ this.getBreed();
};
// end of class Dog
var dog = new Dog(“Buddy”, “Great Dane”);
// test the new toString()
alert(dog );
// Testing instanceof (similar to the is operator)
// (dog is Dog)? yes
alert(dog instanceof Dog);
// (dog is Pet)? yes
alert(dog instanceof Pet);
// (dog is Object)? yes
alert(dog instanceof Object);

Prototype used — replacement technique set correctly The prototype chain is included, so if using C#, the tested instance will run as expected. Also, privileged methods will still function as expected.

Mock namespaces
In C and C#, namespaces are used to minimize name conflicts. For example, in the .NET Framework, namespaces help distinguish the Microsoft.Build.Task.Message class from System.Messaging.Message. JavaScript doesn't have any language-specific features to support namespaces, but it's easy to emulate namespaces using objects. If you want to create a JavaScript library, you can wrap them inside a namespace without defining global functions and classes, like this:
Copy code The code is as follows:

var MSDNMagNS = {};
MSDNMagNS.Pet = function(name) { // code here };
MSDNMagNS.Pet.prototype .toString = function() { // code };
var pet = new MSDNMagNS.Pet("Yammer");

A level of a namespace may not be unique, so it can be created Nested namespace:

Code
Copy code The code is as follows:

var MSDNMagNS = {};
// nested namespace “Examples”
MSDNMagNS.Examples = {};
MSDNMagNS.Examples.Pet = function(name) { // code } ;
MSDNMagNS.Examples.Pet.prototype.toString = function() { // code };
var pet = new MSDNMagNS.Examples.Pet(“Yammer”);

As you can imagine, typing these lengthy nested namespaces can be tiring. Fortunately, library users can easily specify shorter aliases for namespaces:
Copy the code The code is as follows:

// MSDNMagNS.Examples and Pet definition...
// think “using Eg = MSDNMagNS.Examples;”
var Eg = MSDNMagNS.Examples;
var pet = new Eg.Pet(“Yammer”);
alert(pet);

If you look at the source code of the Microsoft AJAX library, you will find that the author of the library used a similar technique to implement naming space (see the implementation of the static method Type.registerNamespace). For more information, check out the sidebar "OOP and ASP.NET AJAX."

Is this how JavaScript should be written?
You have seen that JavaScript supports object-oriented programming very well. Although it is a prototype-based language, it has the flexibility and power to accommodate the class-based programming style common in other popular languages. But the question is: should I write JavaScript code this way? Should the way you program in JavaScript be the same as the way you code in C# or C? Is there a smarter way to emulate functionality not found in JavaScript? Every programming language is different, and what's best for one language may not be best for another.
In JavaScript, you have seen objects inherit objects (unlike classes which inherit classes). Therefore, using a static inheritance hierarchy to build many classes may not be suitable for JavaScript. Perhaps, as Douglas Crockford said in his article Prototypal Inheritance in JavaScript, the way to program in JavaScript is to create a prototype object and use the following simple object function to create a new object, which inherits the original object:
Copy code The code is as follows:

function object(o) {
function F() {}
F.prototype = o;
return new F();
}

Then, since objects in JavaScript are malleable, you can easily create them after , grow the object with new fields and new methods as needed.
This is indeed nice, but it's undeniable that most developers around the world are more familiar with class-based programming. In fact, class-based programming will appear here as well. JavaScript 2.0 will have real classes as per the upcoming version 4 of the ECMA-262 specification (ECMA-262 is the official specification for JavaScript). As a result, JavaScript is evolving into a class-based language. However, it will be several years before JavaScript 2.0 is likely to be widely used. At the same time, it must be clear that current JavaScript can fully read and write JavaScript code in a prototype-based style and a class-based style.

Looking ahead
With the widespread use of interactive thick-client AJAX applications, JavaScript is quickly becoming one of the most important tools for .NET developers. However, its prototype nature may initially surprise developers more accustomed to languages ​​like C, C#, or Visual Basic. I've found that my experience learning JavaScript has been a rich experience, albeit one with some frustrations. I'd love it if this article made your experience a little smoother, because that's exactly what I'm aiming for.
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