0

我根据john resig关于在 javascript 中使用类的想法定义了一个类。

define('class', function() {

    var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
    Class.extend = function(prop) {
        var _super = this.prototype;
        initializing = true;
        var prototype = new this();
        initializing = false;
        for (var name in prop) {
            prototype[name] = typeof prop[name] == "function" &&
                typeof _super[name] == "function" && fnTest.test(prop[name]) ?
                (function(name, fn){
                    return function() {
                        var tmp = this._super;
                        this._super = _super[name];
                        var ret = fn.apply(this, arguments);
                        this._super = tmp;
                        return ret;
                    };
                })(name, prop[name]) :
                prop[name];
        }
        function Class() {
            this.self = this;
            if ( !initializing && this.init )
                this.init.apply(this, arguments);
        }
        Class.prototype = prototype;

        Class.constructor = Class;
        Class.extend = arguments.callee;
        return Class;
    };
    return Class;
   });

然后我尝试在我的 requirejs 文件中使用它,如下所示

define('popup',['class'],
    function (Class) {

        var popup = Class.extend({

            init: function () {
                console.log('init');
            }

        });
     return popup;
    });

我根据requirejs定义从一个简单的html运行代码

<script data-main='script/popup.js' src="script/require.js" ></script>

但它从不运行我的构造函数,即 init 方法

我所有的文件都在脚本文件夹中,因此我没有定义任何路径配置。命中 class.js 和 popup.js 的代码,但它永远不会进入 init 方法。

4

1 回答 1

0

Popup 不是一个对象,而是一个函数,用来获取一个新的对象调用:

var p = new popup();

Class.extend 返回一个新的构造函数,而不是实例化的对象。

ps:之前

Class.extend = function(prop) {

添加

this.Class = function() {};

否则 Class 是未定义的。

于 2013-11-05T10:10:27.017 回答