requirejs加载的javascript文件中的原型函数

时间:2013-05-16 14:27:29

标签: javascript requirejs

当我将此代码放在script.js文件中并包含它运行正常时,

但当我在requirejs加载的javascript文件中实现此代码时,找不到从外部调用的createMapOnOverlay函数,如下所示:

var overlay = new AlarmOverlay(...);
overlay.createMapOnOverlay(..);

alarmoverlay.js:

AlarmOverlay.prototype = new google.maps.OverlayView();

/* constructor */
function AlarmOverlay(bounds, alarmNumber, alarmCssClass) {

    // initialize all properties for an alarm
    this.bounds = bounds;
    this.alarmNumber = alarmNumber;
    this.alarmCssClass = alarmCssClass;
}

AlarmOverlay.prototype.createMapOnOverlay = function(map) {
    // Explicitly call setMap on this overlay
    this.map = map;
    this.setMap(map);
};

AlarmOverlay.prototype.onAdd = function () {


};

AlarmOverlay.prototype.draw = function () {


};

我必须将上面的代码放在以下由requirejs加载的script.js文件中: 但以下代码不起作用

define(function() {
    return function AlarmOverlay(bounds, alarmNumber, alarmCssClass) {

        var self = this;

        self.prototype = new google.maps.OverlayView();

        self.bounds = bounds;
        self.alarmNumber = alarmNumber;
        self.alarmCssClass = alarmCssClass;      


        //AlarmOverlay.prototype.createMapOnOverlay = function(map) {      
           self.map = map;
           self.setMap(map);

        //};

        AlarmOverlay.prototype.onAdd = function() {

        };

        AlarmOverlay.prototype.draw = function() {

        };
    };
});

我如何从google OverlayView派生出来,我可以从外面调用createMapOnOverlay函数,它应该从基类调用setMap?

1 个答案:

答案 0 :(得分:6)

在AlarmOverlay.js中

define(['google'], function(google) {

AlarmOverlay.prototype = new google.maps.OverlayView();

/* constructor */
function AlarmOverlay(bounds, alarmNumber, alarmCssClass) {

    // initialize all properties for an alarm
    this.bounds = bounds;
    this.alarmNumber = alarmNumber;
    this.alarmCssClass = alarmCssClass;
}

AlarmOverlay.prototype.createMapOnOverlay = function(map) {
    // Explicitly call setMap on this overlay
    this.map = map;
    this.setMap(map);
};

AlarmOverlay.prototype.onAdd = function () {


};

AlarmOverlay.prototype.draw = function () {


};


return AlarmOverlay;

}

并在主js文件中:

require(['AlarmOverlay'], function(AlarmOverlay) {
var overlay = new AlarmOverlay(...);
overlay.createMapOnOverlay(..);
}