Tuesday, 15 May 2012

javascript - Prototype inheritance is not working as expected -


I have read my javascript since childhood and after that I should override the manufacturer in case of prototype heritage. But I am surprised to see that the following example gives the same output to the console, even if the override controller statement is commented on. Please enlighten.

  function A () {console.info ("A Creator"); } Function B () {console.info ("b constructor"); } B. Prototype = estrototype; B.prototype.constructor = B; // Do we really need this statement? Console.info ("CP1"); Var B = new B (); Console.info ("CP2"); Before participating the Constructor, there is a problem in your code. You   Prototype  and  are doing both by applying aprototype , 

  bipartotype = aprototype;  

This means that you can not effectively identify the parents of objects created by these functions. Try it

  console.log (New B) Example A, New B (Example B); // True Truth  

This is expected, because B is created by B and B Is made from a prototype but

  console.log (new A () example a, new A () example b); // True Truth  

Whaat? An example of a is an example of how b is? Because since you have b. As prototype is made, in the form of a as a prototype , when an object A is its prototype ( aprototype A < The prototype of the object created with / code> is that the prototype of B exists anywhere in the series, because B.prototype is the same as aprototype , < Code> A to B . .

The correct way to do this is,

  B. Prototype = object. (Aprototype );  

Now, you are creating a prototype with the prototype of A . Therefore, it is A 'is not a prototype, but a object is created on the basis of prototype of A .


Now, if we do not do it

< constructor = b;

constructor property of any object created by B without that code Try printing

  Console.log ((new b ()). Constructor); // [function: A]  

Since the prototype of b still A to prototype , It still refers to the function A . This is why we change it with the B function object.


No comments:

Post a Comment