JavaScript object-oriented (2) and javascript
Constructor and prototype object
Constructor is also a function.newA difference between a function called when an object is created and a common function is that the first letter of the function should be capitalized. However, if the constructor is called as a common function (newKeyword), you should note thatthisPoint to the problem.
var name = "Pomy";function Per(){ console.log("Hello "+this.name);}var per1 = new Per(); //"Hello undefined"var per2 = Per(); //"Hello Pomy"
UsenewWill automatically createthisObject, which belongs to the constructor type and points to the object instance.newKeyword,thisPoint to a global object.
AvailableinstanceofTo detect object types, and each object automatically hasconstructorProperty, pointing to its constructor (literally orObjectObject created by the constructor, pointingObjectThe object created by the custom constructor points to its constructor ).
console.log(per1 instanceof Per); //trueconsole.log(per1.constructor === Per); //true
Each object instance has an internal attribute:[[Prototype]]Which points to the prototype object of the object. Constructor also hasprototypeProperty points to the prototype object. All created objects share the attributes and methods of the prototype object.
function Person(){}Person.prototype.name="dwqs";Person.prototype.age=20;Person.prototype.sayName=function(){ alert(this.name);};var per1 = new Person();per1.sayName(); //dwqsvar per2 = new Person();per2.sayName(); //dwqsalert(per1.sayName == per2.sayName); //true
Therefore, ** the pointer in the instance only points to the prototype, not the constructor. ** ES5 provideshasOwnProperty()AndisPropertyOf()Method to reflect the relationship between the prototype object and the instance
alert(Person.prototype.isPrototypeOf(per2)); //trueper1.blog = "www.ido321.com";alert(per1.hasOwnProperty("blog")); //truealert(Person.prototype.hasOwnProperty("blog")); //falsealert(per1.hasOwnProperty("name")); //falsealert(Person.prototype.hasOwnProperty("name")); //true
Because the prototype object'sconstructorThe attribute points to the constructor itself. Therefore, when rewriting the prototype, you must note thatconstructorAttribute pointing.
Function Hello (name) {this. name = name;} // rewrite the prototype Hello. prototype = {sayHi: function () {console. log (this. name) ;}}; var hi = new Hello ("Pomy"); console. log (hi instanceof Hello); // trueconsole. log (hi. constructor === Hello); // falseconsole. log (hi. constructor === Object); // true
Using the object literal form to rewrite the prototype object changes the properties of the constructor. ThereforeconstructorPointObjectInsteadHello. IfconstructorPoint is very important, you need to manually reset it when rewriting the prototype objectconstructorAttribute
Hello.prototype = { constructor:Hello, sayHi:function(){ console.log(this.name); }};console.log(hi.constructor === Hello); //trueconsole.log(hi.constructor === Object); //false
Using the features of the prototype object, we can easily add custom methods to the JavaScript built-in prototype object:
Array.prototype.sum=function(){ return this.reduce(function(prev,cur){ return prev+cur; });};var num = [1,2,3,4,5,6];var res = num.sum();console.log(res); //21String.prototype.capit = function(){ return this.charAt(0).toUpperCase()+this.substring(1);};var msg = "hello world";console.log(msg.capit()); //"Hello World"
Inheritance
Exploitation[[Prototype]]Feature to implement prototype inheritance. Objects in the literal form are implicitly specified.Object.prototypeFor its[[Prototype]], You can also useObject.create()Display specified, which accepts two parameters: the first one is[[Prototype]]Target object (prototype object), and the second is an optional attribute descriptor object.
Var book = {title: "This is the title of the book" ;}; // same as the following method var book = Object. create (Object. prototype, {title: {retriable: true, enumerable: true, value: "This is the title", wratable: true }});
The literal object is inherited fromObjectAnd more interestingly, implement inheritance between custom objects.
Var book1 = {title: "JS advanced programming", getTitle: function () {console. log (this. title) ;}}; var book2 = Object. create (book1, {title: {retriable: true, enumerable: true, value: "JS authoritative guide", wratable: true}); book1.getTitle (); // "JS advanced programming" book2.getTitle (); // "JS authoritative guide" console. log (book1.hasOwnProperty ("getTitle"); // trueconsole. log (book1.isPropertyOf ("book2"); // trueconsole. log (book2.hasOwnProperty ("getTitle"); // false
When accessingbook2OfgetTitleThe JavaScript Engine executes a search process:book2In its own attributes. If it is found, it is used. If it is not found, it is searched.[[Prototype]]If not found, search for[[Prototype]]Until the end of the inheritance chain. The end is usuallyObject.prototype, Its[[Prototype]]Setnull.
Another way to implement inheritance is to use constructor. Each function has writableprototypeProperty, which is set to inherit fromObject.prototype, You can modify it to change the prototype chain.
Function Rect (length, width) {this. length = length; this. width = width;} Rect. prototype. getArea = function () {return this. width * this. length ;}; Rect. prototype. toString = function () {return "[Rect" + this. length + "*" + this. width + "]" ;}; function Square (size) {this. length = size; this. width = size;} // modify the prototype attribute Square. prototype = new Rect (); Square. prototype. constructor = Square; Square. prototype. toString = function () {return "[Square" + this. length + "*" + this. width + "]" ;}; var rect = new Rect (5, 10); var square = new Square (6); console. log (rect. getArea (); // 50console. log (square. getArea (); // 36
If you want to accesstoString(), You can do this:
Square.prototype.toString = function(){ var text = Rect.prototype.toString.call(this); return text.replace("Rect","Square");}
Related Articles:
DOM notes (12): Prototype objects
DOM note (13): inheritance of JavaScript
Original article: http://www.ido321.com/1586.html