JavaScript Object-oriented understanding and simple examples
I. JavaScript object-oriented concepts:
To illustrate that JavaScript is a thoroughly object-oriented language, it is necessary to start with object-oriented concepts and explore some of the concepts in object-oriented:
1. All things Are object
2. Object has encapsulation and inheritance characteristics
3. Use message communication between objects and objects, each with information hiding
Based on these three points, C + + is a semi-object-oriented semi-oriented process language because, although he implements encapsulation, inheritance, and polymorphism of classes, there are global functions and variables of non-object nature. Java, C # is a complete object-oriented language that organizes functions and variables in the form of classes so that they cannot be separated from the object's existence. But here the function itself is a process, just attached to a class.
However, object-oriented is just a concept or a programming idea, and it should not depend on the existence of a language. For example, Java uses object-oriented thinking to construct its language, which implements such mechanisms as class, inheritance, derivation, polymorphism, and interface. But these mechanisms are just a means of implementing object-oriented programming, not a necessity. In other words, a language can choose the right way to implement object-oriented according to its own characteristics. So, because most programmers first learn or use a similar Java, C + + and other advanced compiler language (Java Although semi-compiled semi-interpretation, but generally as a compilation to explain), so the preconceived acceptance of the "class" this object-oriented implementation, in learning the scripting language, It is customary to use the concept of a class-oriented object language to determine whether the language is an object-oriented language or whether it has object-oriented characteristics. This is one of the important reasons that hinder programmers from learning and mastering JavaScript.
In fact, the JavaScript language implements object-oriented programming in a way called prototypes (prototype) . The following is a discussion of class-based (class-based) object -oriented and prototype-based (prototype-based) object-oriented The difference between the two approaches in constructing an objective world.
Two. Class-based object-oriented and prototype-based object-oriented approach comparisons:
In class-based object-oriented mode, objects (object) are generated by classes (class) . In the prototype-based object-oriented approach, the object is dependent on the constructor (constructor) to exploit The prototype (prototype) is constructed. Give an example of an objective world to illustrate the differences in cognition in two ways. For example, a factory build a car, on the one hand, workers must refer to a drawing, design rules how the car should be manufactured. The engineering drawing here is like the classin the language, and the car is in accordance with this class (class) Manufactured, on the other hand, workers and machines (equivalent to constructor) use various components such as engines, tires, and steering wheels (the equivalent of prototype's various properties) to construct the car.
In fact, there is a debate about who has expressed the object-oriented idea more thoroughly in both ways. But I think the prototype object-oriented is a more thorough object-oriented approach, for the following reasons:
First of all, the object in the objective world is the result of other physical object constructs, and the abstract "drawing" cannot produce "automobile", that is to say, the class is an abstract concept rather than an entity, and the object is produced by an entity;
Second, according to the most basic object-oriented law of all things, the class itself is not an object, but the constructors (constructor) and prototypes (prototype) in the prototype form are themselves objects that other objects have been constructed by way of prototype.
Again, in a class-oriented object language, the state of an object is held by an object instance (instance), and the object's behavior method is held by the class that declares the object, and only the structure and methods of the object can be inherited, whereas in the prototype object-oriented language, the object's behavior, States belong to the object itself, and can be inherited together (reference resources), which is also closer to the objective reality.
Finally, the class-oriented object language, such as Java, allows for the declaration of static and static methods in a class in order to compensate for the inconvenience of using global functions and variables in a procedural language. In fact, the objective world does not exist the so-called static concept, because all things are objects! In the prototype object-oriented language, the existence of global objects, methods or properties is not allowed, and there is no static concept except for the built-in objects (Build-in object). All language elements (primitive) must depend on the existence of an object. However, due to the characteristic of functional language, the object that the language element relies on is changed with the runtime (runtime) context, which is reflected in the change of this pointer. It is this characteristic that is closer to the natural view of "All things belong, the universe is the root of all things". In program Listing 1, window is similar to the concept of the universe.
The context dependency of the object:
varstr = "I am a String object, I declare it here, but I am not independent of existence!" "varobj = {des: "I am an object, I declare here, I do not exist independently." " }; varFun =function() {Console.log ("I am a Function Object!" Who calls me, who I belong to: ", This ); }; Obj.fun=Fun ; Console.log ( This= = = window);//Print TrueConsole.log (window.str = = = str);//Print TrueConsole.log (window.obj = = = obj);//Print TrueConsole.log (Window.fun = = = Fun);//Print TrueFun ();//Print I am a Function Object! Who calls me, who I belong to: WindowObj.fun ();//Print I am a Function Object! Who calls me, who I belong to: objFun.apply (str);//Print I am a Function Object! Who calls me, who I belong to: Str
Three. The most basic object-oriented:
Literal (literal notation) object declaration:
var person = { name: "Zhang San", +, Gender: "Male", function(stuff) { + stuff); } }; = 176; Delete person["age"];
Four. Construct the object using the function constructor:
To create an object using the constructor (constructor):
// The constructor person is itself a function object function person () { // Here you can do some initialization work " // It has a property named prototype person.prototype = {name:" Zhang San ", Age: 26, Gender: "Male", Eat: function (stuff) { Alert ("I'm Eating" + stuff); }} // Constructs an object using the New keyword var p = new person ();
Five. Thorough understanding of the prototype chain (prototype chain):
The __proto__ property and an implicit reference to the object:
functionPerson (name) { This. Name =name; } varp =NewPerson ();//An implicit reference to an object points to the prototype property of the constructor, so printing true hereConsole.log (p.__proto__ = = =Person.prototype); //The prototype itself is an object, so his implicit reference points to the//the prototype property of the Object constructor, and therefore prints trueConsole.log (person.prototype.__proto__ = = =Object.prototype); //The constructor person is itself a function object, so printing true hereConsole.log (person.__proto__ = = = Function.prototype);
Six. Thorough understanding of the prototype chain (prototype chain):
Using the prototype chain Horse->mammal->animal to implement inheritance:
//declaring the Animal object constructor functionAnimal () {}//point the Prototype property of Animal to an object, //can also be directly understood as the prototype of the specified Animal objectAnimal.prototype ={name:"Animal", Weight:0, Eat:function() {alert ("Animal is eating!" ); } } //declaring the Mammal object constructor functionmammal () { This. Name = "Mammal"; } //specifies that the mammal object is prototyped as a Animal object. //This is actually the prototype chain between the creation of the mammal object and the Animal objectMammal.prototype =NewAnimal (); //declaring the Horse object constructor functionHorse (height, weight) { This. Name = "Horse"; This. Height =height; This. Weight =weight; } //Specify the prototype of the Horse object as a Mamal object and continue to build the prototype chain between Horse and mammalHorse.prototype =Newmammal (); //re-Specify the Eat method, which overrides the Eat method inherited from the Animal prototype .Horse.prototype.eat =function() {alert ("Horse is eating grass!" ); } //Validating and understanding the prototype chain varHorse =NewHorse (100, 300 ); Console.log (horse.__proto__===Horse.prototype); Console.log (horse.prototype.__proto__===Mammal.prototype); Console.log (mammal.prototype.__proto__= = = Animal.prototype);
Seven. How to implement JavaScript-class inheritance:
Using simple inheritance to implement class-like inheritance:
//declaring the person classvarperson =class.extend ({_issleeping:true, Init:function(name) { This. _name =name; }, Issleeping:function() { return This. _issleeping; } } ); //declare the Programmer class and inherit the person varProgrammer =person.extend ({init:function(name, issleeping) {//calling the parent class constructor This. _super (name); //set your own State This. _issleeping =issleeping; } } ); varperson =NewPerson ("Zhang San" ); varDiors =NewProgrammer ("Zhangjiang male",false ); //Print TrueConsole.log (person.issleeping ()); //Print FalseConsole.log (diors.issleeping ()); //true here, so print trueConsole.log (personinstanceofPerson && PersoninstanceofClass&& DiorsinstanceofProgrammer &&diorsinstanceofPerson && diorsinstanceofClass);
Eight. JavaScript Private member implementations:
Using closures for information hiding:
//declaring the User constructorfunctionUser (pwd) {//Defining private Properties varPassword =pwd; //Defining Private Methods functionGetPassword () {//returns the password in the closure returnpassword; } //privileged function declaration, which is used by other public methods of the object to access private members through this privileged method This. Passwordservice =function() { returnGetPassword (); } } //Public member DeclarationUser.prototype.checkPassword =function(pwd) {return This. Passwordservice () = = =pwd; }; //verifying the hidden naturevarU =NewUser ("123456" ); //Print TrueConsole.log (U.checkpassword ("123456" ) ); //Print undefinedConsole.log (U.password); //Print TrueConsole.log (typeofU.gepassword = = = "undefined");
JS JavaScript Object-oriented understanding and simple examples