In this article, the prototype of JavaScript is beginning to be formally discussed, which has been a long-winded GOF prototype model. For JavaScript beginners, prototype is a very advanced topic, in fact, not necessarily.
I don't mean to say that it's easy to understand the general usage of prototype. But it's really hard to understand the prototype of the real thing.
Today I'm going to start with the basics of prototype. I've talked about the prototype model above. In fact, in the JavaScript central style is also this meaning. An explanation of the prototype properties of an object in JavaScript is to return a reference to the object type prototype. This is a faint person's explanation. In fact, you specify an object that needs to be replicated.
More text than code, on the code, said the simplest, any class is inherited from the object class:
function A()
{ }
A.prototype=new Object();
In fact, this is equivalent to the object is a prototype of a, which is equivalent to the object's properties and methods copied to a, and the essence of the prototype model!
Well, I've probably learned the basic usage of prototype, so let's see what the prototype is for.
The simplest use is to dynamically extend the methods and properties of the class.
function People()
{
this.Jump=function(){
alert("I can jump");
}
}
Now to expand the method:
People.prototype.Run=function(){
alert("I can run,too");
}
Okay, under test:
var p=new People();
p.Jump();
p.Run();