The ECMA-262 defines an object as a collection of unordered properties that can contain basic values, objects, or functions. We can think of ecmascript objects as a hash: A group of name-value pairs, where values can be used as data or functions. Each function has a prototype attribute, which is an object. The attributes and methods of the prototype object are shared by all instances of the type. Prototype is the prototype of the object created by calling the constructor. The object is bound to its prototype through an internal attribute _ PROTO _, which is visible to developers in Firefox, Safari, and chrome browsers. The prototype of all function objects defaults to the prototype of the object. For example:
<script language="javascript" type="text/javascript">
function Person(name, address) {
this.name = name;
this.address = address;
}
Person.prototype.say = function () {
alert(this.name);
}
var person1 = new Person("Feng", "Henan");
var person2 = new Person("Lee", "Beijing");
alert(person1 instanceof Person);//true
alert(person1 instanceof Object); //true alert(Person.prototype.isPrototypeOf(person1)); //true
alert(Person.prototype.isPrototypeOf(person2)); //true
</script>
The constructor person is used to create a new instance. The prototype of instance person1 (_ PROTO _) points to person. prototype. The prototype of person. Prototype points to object. prototype. The prototype chain created by the above Code is as follows:
The following example shows the charm of the dynamic characteristics of the prototype, so as to avoid a magical bug in the program. You need to use Firefox for debugging.
<Script language = "JavaScript" type = "text/JavaScript">
Function person (){
}
VaR person1 = new person ();
Person. Prototype. sayold = function (){
Alert ("old test ");
};
// Person. Prototype = {
// Name: "Feng ",
// Address: "Henan ",
// Say: function (){
// Alert (this. Name );
//}
//};
// Person1.say (); the error cannot be called.
Person1.sayOld ();
Alert (person1. _ proto _. constructor );
Var person2 = new Person ();
Alert (person2. _ proto _. constructor );
Alert (Person. prototype. constructor );
</Script>
Note that person1 is an instance created before the sayOld method is added. The sayOld () method is called normally. The firebug debugging information is as follows:
Now, comment out person1.sayOld () and restore the commented-out code to normal,
However, the person1.say () method cannot be called, because we have rewritten the prototype, and person1 points to the original prototype. The original prototype does not include the say method. The prototype is as follows: