JS用函数原型摸拟面向对象。。很怪异。。
function Parent(id, name) //定义父类
{
this._id = id; //定义对象属性
this._name = name;
if (typeof Customer._init == "undefined")
{
Customer.prototype.Say = function() //定义对向方法,只执行一次
{
alert("my name is " + this._name);
}
Customer._init = true;
}
}
function ChildCustomer(id, name) //定义子类
{
Customer.call(this, id, name); //利用对象冒充,实现继承对象属性 (但不包括方法)
if (typeof ChildCustomer._init == "undefined")
{
ChildCustomer.prototype.NewMethod = function() //定义子类方法
{
alert("哈哈,子类方法");
}
ChildCustomer._init = true;
}
}
//这句重要,将父类prototype的原型赋给子类原型,相当于继承父类的方法
//并且这句必需在实例化对象前,声明子类父类后面。。。
ChildCustomer.prototype = new Customer();
var objCus = new ChildCustomer(2, "张三");
objCus.Say();