zoukankan      html  css  js  c++  java
  • 使用js模拟类继承小例子

    代码
    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();


  • 相关阅读:
    图像处理国际会议
    [2015更新]用Word2007写CSDN博客
    【超详细教程】使用Windows Live Writer 2012和Office Word 2013 发布文章到博客园全面总结
    奇异秀App:奇异秀秀奇异,用大头视频来拜年
    通俗讲解傅里叶级数
    LIBSVM的使用方法
    VC6.0的工程设置解读Project--Settings
    HOG:从理论到OpenCV实践
    如何在 Kaggle 首战中进入前 10%
    linux学习(2)
  • 原文地址:https://www.cnblogs.com/xhan/p/1779096.html
Copyright © 2011-2022 走看看