javascript - Questions about prototype chain
PHP中文网
PHP中文网 2017-06-14 10:53:03
0
3
723
function Shape(){
    this.name='Shape';
    this.toString=function(){
        return this.name;
    };
}

function TwoDShape(){
    this.name='2D shape';
}

function Triangle(side,height){
    this.name='Triangle';
    this.side=side;
    this.height=height;
    this.getArea=function(){
        return this.side*this.height/2;
    };
}

TwoDShape.prototype=new Shape();
Triangle.prototype=new TwoDShape();

var my=new Triangle(5,10);
my.getArea();//25

my.toString();//"Triangle"

1.When my.toString() is called, what is the execution path of the JavaScript engine?

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
滿天的星座
var my=new Triangle(5,10);//[1]

my.getArea();//25 [2]

my.toString();//"Triangle" [3]

[1]. Create Triangle instance object my,

this.name='Triangle';
this.side为 5;
this.height为 10;

[2] Call the method getArea on the Triangle instance object my
[3] Call the method toString on the Triangle instance object my and find that it does not exist on the current object. Follow the prototype chain to find the TwoDShape instance object. If it does not exist yet, go to the Shape instance. Go up and look for the object, OK, find it.
The this object at this time is the Triangle instance object my, the name attribute value on it is Triangle, and the output is

过去多啦不再A梦

1: First understand the relationship between types and instances. Shape is a type (abstract), var shape = new Shap(); shape is an instance;
2: The question is too vague, var shape = new Shap(); and What is the relationship between the constructor of var sh = Shape() => The constructor of shape is Shape.prototype.constructor; (How can shape and sh be related~)
3: Why not inherit directly? Designed like this;

代言

You can see it by splitting it all. First, look at the operation logic of new, TwoDShape.prototype = new Shape();It does three things

TwoDShape.prototype = {};
TwoDShape.prototype.__proto__ = Shape.prototype;
Shape.call(TwoDShape.prototype);

Same reason

Triangle.prototype = {};
Triangle.prototype.__proto__ = TwoDShape.prototype;
TwoDShape.call(Triangle.prototype);
var my = {};
my.__proto__ = Triangle.prototype;
Triangle.call(my, 5, 10);

When executing my.toString(), start looking for toString from my's own members. If not, search up along __proto__, and finally find my.__proto__.__proto__ (that is, TwoDShape. Found toString in prototype

)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template