国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

javascript - Questions about prototype chain
PHP中文網(wǎng)
PHP中文網(wǎng) 2017-06-14 10:53:03
0
3
822
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中文網(wǎng)
PHP中文網(wǎng)

認(rèn)證0級(jí)講師

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夢(mèng)

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