悟透javascript代码摘录


function Class(){
var aDefine = arguments[arguments.length-1];//最后一个参数为类定义
if (!aDefine)//没有参数就返回
{
return;
}
var aBase = arguments.length > 1?arguments[0]:object;//解析基类
function prototype_(){};//构造prototype的临时函数,用于挂接原型链
prototype_.prototype = aBase.prototype;//准备传递prototype
var aPrototype = new prototype_();//建立类要用的prototype

for (var member in aDefine)//复制类定义到当前类的prototype
{
if (member != "Create")//构造函数不用复制
{
aPrototype[member] = aDefine[member];
}
}
//如果有构造函数
if (aDefine.Create)
{
var aType = aDefine.Create;//类型即为该构造函数
}
else{//否则为默认构造函数。
aType = function(){
this.base.apply(this,arguments);
}
}

aType.prototype = aPrototype; //设置类(构造函数)的prototype
aType.Base = aBase; //设置类型关系
aType.prototype.Type = aType; //为本类对象扩展一个Type属性
return aType; //返回构造函数作为类
}

//根类object定义
function object(){};//定义小写的object根类,用于实现最基础的方法等
object.prototype.isA = function(aType){//判断是否属于某类型
var self = this.Type;
while (self)
{
if(self == aType) return true;
self = self.Base;
}
return false;
}
//调用基类构造函数
object.prototype.base = function(){
var Caller = object.prototype.base.caller;
Caller && Caller.Base && Caller.Base.apply(this,arguments);
}

//应用效果
//默认派生自object基本类
var Person = Class({
Create:function(name,age){
this.base();
this.name = name;
this.age = age;
},
sayHello:function(){
alert("Hi,I am " + this.name + ", " + this.age + " years old.");
}
});
//Employee派生自Person
var Employee = Class(Person,{
Create:function(name,age,salary){
this.base(name,age);//调用基类的构造函数
this.salary = salary;
},
showMeTheMoney:function(){
alert(this.name + "'s salary is: $" + this.salary);
}
});

var wml = new Person("Wu Mingli",29);
//wml.sayHello();
//var xyd = new Employee("Xu yedong",28,7500);
//xyd.showMeTheMoney();
var lyp = new wml.Type("Lv yaping",25);
lyp.sayHello();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值