prototype--prototypes for dynamically adding properties and behaviors to objects
First define a constructor function
Small accessory function Gadget (name, color) {this.name = Name;this.color = Color;this.whatareyou = function () {return ' I am ' + this.co Lor + ' + this.name;} This.get = function (what) {return this[what];//object is similar to array, JS [] can be subscript or object's property}}
Adding properties and methods using prototype
/* Use prototype to add properties and methods */gadget.prototype.price = 100;//Add Property Gadget.prototype.rating = 3;//increase Behavior = = Method = = or called function Gadget.prototype.getInfo = functions () {return ' level: ' + this.rating + ', Price: ' + this.price;};/ * can also be bulk replaced or added */gadget.prototype = {price:100,rating:3,getinfo:function () {//Accessible raw Properties <span style= "White-space:pre" ></span>return ' name: ' +this.name+ ', rank: ' + this.rating + ', Price: ' + This.price;}}; var toy = new Gadget (' webcam ', ' black '), alert (Toy.getinfo ());//access to new methods, or access to existing properties and methods
/* Property Traversal and judgment */
For (I-in toy) {if (typeof (Toy[i])! = "function")//Traverse out all the properties and attribute values that can be accessed on toy alert (i + ' = ' + Toy[i]);}
The judging property is not the original for (prop in toy) {<span style= "White-space:pre" ></span>if (Toy.hasownproperty (prop)) {< Span style= "White-space:pre" ></span>alert ("Original:" +prop + ' = ' + Toy[prop]); <span style= "White-space:pre" ></span>}}
Each object has a isprototypeof method that determines whether the current object is a prototype of another object
/*every object also gets the isPrototypeOf () method. * This method tells your whether that specific object is used as a prototype of another object. Each object has a isprototypeof method that determines the current object is not another object of prototype* */var monkey = {hair:true,feeds: ' Bananas ', breathes: ' Air '};function Human (name) {this.name = Nam e;} Human.prototype = Monkey;var George = new Human (' George '); Alert ("monkey.isprototypeof (george) = = =" + Monkey.isprototypeof (George));
Summarize:
Prototype can be viewed as an additional object, referencing a prototype object on the constructor, which has properties and methods;
The object generated by the constructor also naturally links the prototype object, and can treat the properties and methods of the prototype object as its own;
Of course, the original properties and the properties obtained through prototype are somewhat different, at least through hasOwnProperty can determine whether this property is its own native property;
In addition, a.isprototypeof (b) can be used to determine whether a is a B prototype.
JavaScript Object-Oriented programming (3) prototype introduction