使用js模拟类继承小例子

ExpandedBlockStart.gif 代码
Function.prototype.method  =   function  (name, func) {
    
if  ( ! this .prototype[name]) {
        
this .prototype[name]  =  func;
    }
    
return   this ;
};
var  extend  =   function  (subType, superType) {
    
// 创建临时对象,临时对象的原型指针指向父类型原型,并让子类型原型对象指向临时对象。从而通过原型链继承父类型共享方法和属性
     function  F() { };
    F.prototype 
=  superType.prototype;
    subType.prototype 
=   new  F();

    
// 重新设置子类型原型对象constuctor属性,已支持正确的instanceof操作符类查询对象的正确类型
    subType.prototype.constructor  =  subType; 
    
// 设置子类型base属性为父类型,方便借用构造函数继承父类型属性
    subType.base  =  superType;

    
// 检查父类型原型constructor属性是否正确设置,如果没有帮它正确设置
     if  (superType.prototype.constructor  ===  Object.prototype.constructor) {
        superType.prototype.constructor 
=  superType;
    }

};

function  Parent(name) {
    
this .name  =  name;
}

Parent.method(
" sayHello " function  () {
    alert(
this .name);
})
.method(
" method1 " , function (){})
.method(
" method2 " , function (){});

function  Child(name, age) {
    Child.base.call(
this , name);
    
this .age  =  age;
}
extend(Child, Parent);
Child.method(
" sayAge " function  () {
    alert(
this .age);
})

var  p  =   new  Parent( " aa " );

p.sayHello();

var  c  =   new  Child( " bb " , 11 );
c.sayHello();
c.sayAge();


转载于:https://www.cnblogs.com/xhan/archive/2010/07/16/1779096.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值