JavaScript面向对象编程指南 读书笔记6-01
原型链
JavaScript中的每个函数都有一个指向某一对象的prototype属性。该函数被new操作符调用的时候会创建并返回一个对象,并且该对象中会有一个指向其原型对象的秘密链接。通过该秘密链接,就可以在新建的对象中调用相关原型对象的方法和属性。
而原型对象自身也具有对象固有的普遍特征,因此本身也包含了指向原型的链接,因此形成了一条链,我们称之为原型链。
原型链示例
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();//将对象直接创建在TwoDShape对象的prototype属性中
Triangle.prototype = new TwoDShape();
//将对象的constructor属性进行重置
TwoDShape.prototype.constructor = TwoDShape;
Triangle.prototype.constructor = Triangle;
var my = new Triangle(5,10);
my.getArea();
my.toString();//调用my对象所继承的toString()方法
#笔记##读书笔记#


