JavaScript面向对象
面向对象的编程思想三大要素:
l 封装
l 继承
l 多态
JavaScript如何实现OOP
l 封装(Wrap)
JavaScript的对象封装,主要依靠function来实现。以下是一个简单的示例:
//*********************************************
// 定义Pet(宠物)对象
//*********************************************
function Pet() {
//名称
this.name = null;
//颜色
this.color = null;
//获取名称
this.getName = function() {
return this.name;
};
//设置名称
this.setName = function(newName) {
this.name = newName;
};
//获取颜色
this.getColor = function() {
return this.color;
};
//设置颜色
this.setColor = function(newColor) {
this.color = newColor;
};
//定义一个需要实现的方法
this.getFood = null;
//获取宠物的描述信息
this.toString = function() {
return "The pet is " + this.name +",it's "
+this.color+",and it likes "+this.getFood()+".";
};
}
l 继承(inheritance)
JavaScript的继承的实现主要依靠prototype(原型)来实现,下面为Pet类编写一个子类。
//*********************************************
// 定义Cat(猫)对象
//*********************************************
function Cat() {
//实现Pet中定义的getFood方法
this.getFood = function() {
return "fish";
};
}
//声明Cat的原型,即Cat的父类
Cat.prototype = new Pet;
多层次继承
//*********************************************
// 定义PersianCat(波斯猫)对象
//*********************************************
function PersianCat() {
}
//声明PersianCat的原型,即PersianCat的父类
PersianCat.prototype = new Cat;
l 重载(override)与多态(Polymorphism)
//重载Pet的toString方法
PersianCat.prototype.toString = function() {
return "It's just a persian cat.";
};