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


  • 相关阅读:
    AngularJS中$http服务的简单用法
    js变量作用域及访问权限的探讨(2)
    javascript中类的属性访问权限研究(1)
    zoom:1-hasLayout
    JS 继承(类式 与 原型式)
    迷你版jQuery——zepto核心源码分析
    移动互联网终端的touch事件,touchstart, touchend, touchmove
    WEBAPP开发技巧总结
    JQuery flot API文档 中文版
    jQuery插件Flot实战Demo
  • 原文地址:https://www.cnblogs.com/xhan/p/1779096.html
Copyright © 2011-2022 走看看