Home > Web Front-end > JS Tutorial > Thoughts on the inability to display the inheritance mechanism using dynamic prototype methods_javascript skills

Thoughts on the inability to display the inheritance mechanism using dynamic prototype methods_javascript skills

WBOY
Release: 2016-05-16 18:40:29
Original
1229 people have browsed it
Copy code The code is as follows:





It was strange at first to think about this code, why Can't run it? So I started thinking based on the author's narrative (the author's explanation behind this code is very convoluted, and you won't be able to understand what he is talking about without reading it several times), and finally I figured it out.
We already know that the process of creating an object in the form of var anObject = new aFunction() can actually be divided into 3 steps:
(1) Create a new object
(2) Convert the object’s built-in prototype object Set as the prototype object referenced by the constructor portotype
(3) Call the constructor as the this parameter to complete the initialization work such as member setting

Please pay attention to step (2). It turns out that
Copy code The code is as follows:

var oTriangle1 = new Triangle(12,4);


When this sentence is executed, oTriangle1.prototype = Triangle.prototype; is executed internally (of course, the Triangle.prototype object itself has no actual properties and methods at this time) and then continues execution until (3) ) step, run the function body, and run the function body for the first time to

Copy the code The code is as follows:

Triangle.prototype = new Polygon();


But after this sentence is executed, oTriangle1.prototype can no longer be assigned a value (that is, oTriangle1.prototype = Triangle cannot be executed) .prototype;), then the program executes
Copy code The code is as follows:

Triangle.prototype .getArea = function() {
return this.base * this.hei * 0.5;
};

But it is too late at this time, the oTriangle1.prototype object is It will not own this method. The only object that owns this method is the object created by new Polygon() just now, so there is the result of the last line of comments in the program. But the Triangle object created next can run normally. Please look at the code below:

Code
Copy code The code is as follows:





As for the reason, it is what I analyzed earlier. At this time, it is executed internally oTriangle2.prototype=Triangle.prototype;The prototype object is assigned an object reference with actual properties and methods.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template