首页 > js模块之间如何继承和调用?

js模块之间如何继承和调用?

例如有
a.js

define(['jquery'],functions($){
    function A(options){
        this.options = options;
        this.init();
    }

    A.prototype.getData = function(){
        //do something
    };

    A.prototype.init = function(){
        var self = this;
        $(function(){
            self.getData();
        });
    };

    return A;
});

b.js

define(['jquery'],functions($){
    function B(options){
        this.options = options;
        this.init();
    }

    B.prototype.getData = function(){
        //do something
    };

    B.prototype.init = function(){
        var self = this;
        $(function(){
           self.getData();
        });
   };

   return B;
});

B如何继承A,调用A里面的方法和值?
还是说用依赖就可以了,那依赖的话要怎么写?


js的继承是使用 原理是使用原型链进行继承(prototype)说明

而模块化的原理是使用闭包进行访问权限控制,暴露出接口,当然现在有很多封装好的模块化类库,比如seajs,modjs,requirejs等等


继承和调用依然用js的方式去做
我只会coffee 大概写成这个样子

a.coffee

define [],()->
    class A
        constructor: () ->
            @init=()->
                @getData()
            @init()

        getData:()->
            console.log "I am A"

b.coffee

define ['a'],(A)->
    class B extends A
        constructor: () ->
            @init=()->
                console.log "I am B"
            @init()

        getData:()->
            super

index.coffee

require [
    'b'
],(B)->
    # class B的构造函数 输出 `I am B`
    b=new B()
    # b调用父类的 getData() 输出 `I am A `
    b.getData()

继承的部分和普通的JS实现继承的方法没有太大差别,你可以参考下面的实现方式,另外,如果用方式这种继承的话,init方法的调用位置是值得商榷的。

b.js:

define(['jquery', 'a'], function ($, A) {
  function B(options) {
    this.options = options;
  }

  //继承A
  B.prototype = new A();
  B.prototype.constructor = B;
  //保存父类的引用
  B.prototype.parent = A.prototype;

  //复写A中的方法
  B.prototype.getData = function () {
    //do something
  };

  B.prototype.init = function () {
    //如果需要的话,可以调用父类的方法
    this.parent.init.call(this);
    console.log('inited');
  };

  return B;
});

参考

Inheritance

【热门文章】
【热门文章】