1、关于原型链的示例
<script type="text/javascript">
(function(){
function Shape(){
this.name = 'Shape';
this.toString = function(){
return this.name;
}
}
function Triangle(side,height){
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function(){
return this.side * this.height / 2;
}
}
Triangle.prototype = new Shape();
Triangle.prototype.constructor = Shape;javascript
var my = new Triangle(5,10);
console.log(my.getArea());
console.log(my.toString());java
/*
下面看看javascript 引擎是怎么作的
1.遍历my对象的全部属性,没有找到toString()方法
2.去查看my.__proto__指向的对象,该对象是构建继承关系时建立的new Shape()
3.在new Shape()对象中找到了toString()方法
4.因为是my对象调用的toString()方法,this指向的是my
*/ide
console.log('============我是分隔符=============');
})();
</script>this
2、将共有属性迁移到原型中,依旧继承实例对象
<script type="text/javascript">
(function(){
function Shape(){
this.name = 'Shape';
}
Shape.prototype.toString = function(){
return this.name;
}spa
function Triangle(side,height){
this.name = 'Triangle';
this.side = side;
this.height = height;
}prototype
Triangle.prototype = new Shape();//这里先构建继承,再扩展原型,不然下面的getArea()将会丢失对象
Triangle.prototype.getArea = function(){
return this.side * this.height / 2;
}继承
var my = new Triangle(5,10);
console.log(my.getArea());
console.log(my.toString());
console.log('============我是分隔符=============');
})();ip
</script>原型链
3、只继承于原型
<script type="text/javascript">
(function(){
/*
把共有的属性和方法添加到原型中去,这样依靠原型就能够实现继承的构建了,
而不是继承 new Shape()建立的实体,这样能够提升效率
*/
function Shape(name){
this.name = name;
}
Shape.prototype.toString = function(){
return this.name;
}
function Triangle(name,side,height){
this.name = name;
this.side = side;
this.height = height;
}
Triangle.prototype =Shape.prototype; //这里仍是先构建继承关系
Triangle.constructor.prototype = Triangle;
Triangle.prototype.getArea = function(){
return this.side * this.height / 2;
}
/*
Triangle.prototype.toString = function(){ //这里覆盖了Shape的toString()方法
return '这里是Triangle的toString()方法';
}*/
var s = new Shape('shape');
var t = new Triangle('triangle',5,10);
console.log(t.toString());
console.log(t.getArea());
console.log(s.toString());
/*
注意:这里继承的是原型,第二种继承的是实例对象,省去了实例属性和方法的查找
*/
console.log('============我是分隔符=============');
})();
</script>
4、临时构造器 new F()继承
<script type="text/javascript">
(function(){
function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
return this.name;
}
function Triangle(side,height){
this.side = side;
this.height = height;
}
//临时构造器 new F()
var F = function(){}
F.prototype = Shape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'triangle';
Triangle.prototype.getArea = function(){
return this.side * this.height / 2;
}
/*
这样作的好处是让父对象的属性摆脱子对象对其的影响,
回看第三种只继承于原型中注释掉的,Triangle覆盖toString(),
你会发现Shape()的toString()也发生了改变,有时候这种并不合适
而当前这种只是修改了new F()实例的toString(),并不会影响到Shape()的toString() */ })(); </script>