Constructors and prototype objects
The constructor is also a function, with the function that is new
called when the object is created, one difference from a normal function is that its initials should be capitalized. However, if you use constructors as normal function calls (missing new
keywords), you should be aware this
of the problem that points to.
var"Pomy";function Per(){ console.log("Hello "+this.name);}varnew Per(); //"Hello undefined"var per2 = Per(); //"Hello Pomy"
new
when used, the object is automatically created with the this
type constructor type, point to object instance, missing new
keyword, and this
point to the global object.
You can use it instanceof
to detect object types, and each object automatically has a property when constructor
it is created, pointing to its constructor (the object created by the literal form or Object
constructor, pointing Object
to the object that the custom constructor creates, and pointing to its constructor).
consoleinstanceof Per); //trueconsole//true
Each object instance has an internal property: A [[Prototype]]
prototype object that points to the object. The constructor itself also has prototype
properties that point to the prototype object. All created objects share the properties 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 ();p er1.sayname (); //dwqs var per2 = new person ();p er2.sayname (); //dwqs alert (per1.sayname = = Per2.sayname); //true
Therefore, the pointer in the * * instance only points to the prototype, not to the constructor. **ES5 provides hasOwnProperty()
and isPropertyOf()
methods to react to the relationship between a prototype object and an 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 properties of the prototype object point to the constructor
constructor itself, you need to be aware constructor
of the point-in-time behavior of the property when overriding the prototype.
function hello (name) { this . Name = name;} //rewrite prototype Hello.prototype = {Sayhi:function () { console.log (this . Name); }}; var hi = new Hello ( " Pomy ""); Console.log (hi instanceof Hello); //true console.log (hi.constructor = = = Hello); //false console.log (hi.constructor = = = object ); //true
Overwriting a prototype object with object literals alters the properties of the constructor, so it constructor
points Object
to, instead of Hello
. If constructor
pointing is important, you need to manually reset its properties when overwriting the prototype object constructor
Hello.prototype = { constructor:Hello, sayHi:function(){ console.log(this.name); //trueObject//false
Using the characteristics of the prototype object, we can easily add a custom method on the JavaScript built-in prototype object:
Array. prototype.sum= function(){ return This. Reduce ( function(prev,cur){ returnPrev+cur; });};varnum = [1,2,3,4,5,6];varres = Num.sum (); Console.log (res);//21String. Prototype.capit = function(){ return This. CharAt (0). toUpperCase () + This. SUBSTRING (1);};varmsg ="Hello World"; Console.log (Msg.capit ());//"Hello World"
Inherited
With the [[Prototype]]
feature, the prototype can be inherited, the literal form of the object is implicitly specified Object.prototype
as it [[Prototype]]
, or can be Object.create()
specified by the display, which accepts two parameters: the first is the [[Prototype]]
object (prototype object) to point to, The second is an optional property descriptor object.
var book = { title:"这是书名";};//和下面的方式一样varObject.create(Object.prototype,{ title:{ configurable:true, enumerable:true, value:"这是书名", wratable:true }});
The literal object inherits from the default Object
, and the more interesting use is to implement inheritance between custom objects.
varBook1 = {title:"JS Advanced Programming",GetTitle:function(){Console. log ( This. title); }};varBook2 = Object.create (book1,{title:{Configurable: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 book2
the property is accessed getTitle
, the JavaScript engine performs a search process: Looking for its own property now, finding it, or searching if it is not found, and, book2
[[Prototype]]
if not found, continuing to search the prototype object until the end of the [[Prototype]]
inheritance chain. The end is usually Object.prototype
, and it is [[Prototype]]
set to null
.
Another way to implement inheritance is to take advantage of constructors. Each function has a writable prototype
property, which is set by default to inherit from Object.prototype
, and can be overridden to alter 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 propertySquare.prototype =NewRect (); Square.prototype.constructor = Square; Square.prototype.toString = function(){ return "[Square]+ This. length+"*"+ This. width+"]";};varRect =NewRect (5,Ten);varSquare =NewSquare (6); Console.log (Rect.getarea ());//50Console.log (Square.getarea ());//36
If you want to access the parent class toString()
, you can do this:
function(){ var text = Rect.prototype.toString.call(this); return text.replace("Rect","Square");}
Related articles:
Dom Notes (12): Another discussion of prototype objects
Dom Notes (13): How JavaScript is inherited
Original: http://www.ido321.com/1586.html
JavaScript Object-oriented Essentials (ii)