JavaScript does not classify and instance the concept, but uses the prototype (prototype) to implement object-oriented programming.
Prototyping is when we want to create xiaoming this specific student, we do not have a student type available, what should we do? There happens to be a ready-made object:
var robot = { name:' Robot ', height:1.6, run:function () { Console.log (this. name+ ' is running ... ');} ;
We can rename it to student, and then create a xiaoming:
var Student = { name:' Robot ', height:1.6, run:function () { Console.log (this. name+ ' is running ... ');} ; var xiaoming={ name:"Xiaoming" }; Xiaoming._proto_=student;
The last line of code points the prototype of Xiaoming to the object student, which looks xiaoming as if it were inherited from student:
Xiaoming.name; // ' Xiao Ming ' Xiaoming.run (); // Xiao Ming is running ...
Xiaoming has its own name property, but does not define the run () method, however, because Xiaoming inherits from student, as long as student has the run () method, Xiaoming can also call:
The difference between JavaScript's prototype chain and Java's class is that it has no concept of class, all objects are instances, so-called inheritance is simply a prototype of an object pointing to another object.
If you point the Xiaoming's prototype to another object
var Bird = { function () { Console.log (this. Name + ' is flying ... '); = Bird;
Now the xiaoming has been unable to run (), he has become a bird:
Xiaoming.fly ();///Xiao Ming is flying ...
During the runtime of the JavaScript code, you can turn the Xiaoming bear student into bird, or become any object.
When writing JavaScript, do not use obj._proto_ directly to change the prototype of an object, and the low version of IE page can not be used _proto_. The Object.create () method can pass in a prototype object and create a new object based on the prototype, but none of the new objects have any properties, so we can write a function to create the xiaoming:
//prototype objects: varStudent ={name:' Robot ', Height:1.2, run:function() {Console.log ( This. name+ ' is running ... '); } }; functioncreatestudent (name) {//Create a new object based on the student prototype: vars =object.create (Student); //Initializing ObjectsS.name=name; returns; } varXiaoming=createstudent (' Xiao Ming ')); Xiaoming.run ();//Xiao Ming is running ...Xiaoming._protp_===student;//true
JS Object-Oriented programming