search

Home  >  Q&A  >  body text

javascript - Questions about prototype chain

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中文网2746 days ago728

reply all(3)I'll reply

  • 滿天的星座

    滿天的星座2017-06-14 10:55:03

    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

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-14 10:55:03

    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;

    reply
    0
  • 代言

    代言2017-06-14 10:55:03

    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

    )

    reply
    0
  • Cancelreply