JavaScript object-oriented skills (2)
Constructor and prototype object
Constructor is also a function.new
A 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 (new
Keyword), you should note thatthis
Point to the problem.
var name = "Pomy";function Per(){ console.log("Hello "+this.name);}var per1 = new Per(); //"Hello undefined"var per2 = Per(); //"Hello Pomy"
Usenew
Will automatically createthis
Object, which belongs to the constructor type and points to the object instance.new
Keyword,this
Point to a global object.
Availableinstanceof
To detect object types, and each object automatically hasconstructor
Property, pointing to its constructor (literally orObject
Object created by the constructor, pointingObject
The 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 hasprototype
Property 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 <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxwcmUgY2xhc3M9 "brush: java;"> 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'sconstructor
The attribute points to the constructor itself. Therefore, when rewriting the prototype, you must note thatconstructor
Attribute 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. Thereforeconstructor
PointObject
InsteadHello
. Ifconstructor
Point is very important, you need to manually reset it when rewriting the prototype objectconstructor
Attribute
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.prototype
For 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 fromObject
And 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 accessingbook2
OfgetTitle
The JavaScript Engine executes a search process:book2
In 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 writableprototype
Property, 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