Introduction to JavaScript Object-Oriented Programming (3) prototype
Prototype: A prototype used to dynamically add attributes and actions to an object.
First define a constructor
// Accessory function Gadget (name, color) {this. name = name; this. color = color; this. whatAreYou = function () {return 'I am' + this. color + '+ this. name;} this. get = function (what) {return this [what]; // an object is similar to an array. js [] can contain subscripts or object attributes }}
Add attributes and methods using prototype
/* Use prototype to add attributes and Methods */Gadget. prototype. price = 100; // Add the attribute Gadget. prototype. rating = 3; // Add behavior = Method = or call the function Gadget. prototype. getInfo = function () {return 'level: '+ this. rating + ', price:' + this. price ;};/* can also be replaced or added in batches */Gadget. prototype = {price: 100, rating: 3, getInfo: function () {// you can access the original attribute 'Return 'name:' + this. name + ', level:' + this. rating + ', price:' + this. price ;}}; var toy = new Gadget ('webcam ', 'black'); alert (toy. getInfo (); // you can access the new method or the original attributes and methods.
/* Attribute traversal and judgment */
For (I in toy) {if (typeof (toy [I])! = "Function") // traverses all the attributes and attribute values that can be accessed on toy. alert (I + '=' + toy [I]);}
// Determine whether the property is original for (prop in toy) {if (toy. hasOwnProperty (prop) {alert ("Original:" + prop + '=' + toy [prop]);}
Each object has an isPrototypeOf method, which is used to determine whether the current object is another prototype of the object.
/* Every object also gets the isPrototypeOf () method. * This method tells you whether that specific object is used as a prototype of another object. each object has an isPrototypeOf method, which is used to determine whether the current object is another prototype **/var monkey = {hair: true, feeds: 'banas', breathes: 'air'}; function Human (name) {this. name = name;} Human. prototype = monkey; var george = new Human ('George '); alert ("monkey. isPrototypeOf (george) = "+ monkey. isPrototypeOf (george ));
Summary:
You can regard prototype as an additional object and reference a prototype object on the constructor. This object has some attributes and methods;
The object generated by the constructor naturally links the prototype object, and the attributes and methods of the prototype object can be considered as their own;
Of course, the original attribute and the attribute obtained through prototype are still somewhat different. At least hasOwnProperty can be used to determine whether this attribute is its own native attribute;
In addition, a. isPrototypeOf (B) can be used to determine whether a is a prototype of B.