javascript继承--prototype简单解释

javascript继承==>prototype简单使用

1,原型链实例

2,将公共属性迁移到原型中

3,只继承原型

4,临时构造器--new F()使用

下面写的简单实例:

 

function shape(){}

shape.prototype.name = 'name';

shape.prototype.toString = function(){

return this.name

}

 

function tweShape(){}

var F = function(){}

F.prototype = shape.prototype;

tweShape.prototype = new F();

tweShape.prototype.constructor = tweShape;

tweShape.prototype.name= '2d Shape';

 

function triangle(side,height){

    this.side = side;

    this.height = height;

}

var F = function(){}

F.prototype = tweShape.prototype

triangle.prototype = new F();

triangle.prototype.constructor = triangle;

triangle.prototype.name = 'Triangle';

triangle.prototype.getArea = function(){

    return this.side * this.height / 2;

}

 

chrom浏览器console控制台进行调试如下:

var tri = new triangle(10,15);

tri.getArea();

==>75

 

tri.constructor

==>function triangle(side,height){

            this.side = side;

            this.height = height;

      }

 

var twe = new tweShape();

twe.constructor;

=>function tweShape(){}

twe.name;

=>2d Shape

 

var shp = new shape();

shp.construtor;

=>function shape(){}

shp.name

=>name

 

如果我们不使用临时构造器,在实例化shape和tweShape执行的原型都是triange,输入对应的实例化对象

twe.name 或者 shp.name结果都是

==>Triangle

你可能感兴趣的:(js prototype)