javascript - YUI3 对象和带有模块的命名空间

标签 javascript yui3

我无法理解如何在 YUI3 中命名空间和实例化对象。在下面的示例中,我正在创建一个 YUI3 模块,将其加载到 YUI.use 方法中并尝试通过命名空间实例化我的对象。但这不起作用,有人可以指出原因吗?尝试实例化新对象时出现错误:“对象不是函数”。

test-module.js

YUI.add('test-module', function(Y){ 
var TestModule = {
    url: '',        

    /* Example function */
    doExample: function(){          
        console.log("doExample called");        
        }
}
// expose this back to the Y object
Y.namespace('SANDBOX.Test').TestModule = TestModule;
}, 1.0, {requires:['node']});

index.html

YUI({
    modules:{
        'test-module': {
            fullpath: 'js/test-module.js',
            requires: ['node']
        }
    }
}).use('test-module', function(Y){
    var testModule = new Y.SANDBOX.Test.TestModule(); //this throws the error
    testModule.doExample();
});

最佳答案

你的代码中的问题(你说它抛出异常)是你在一个普通对象上使用 new () 。这不是构造函数。

换行

var testModule = new Y.SANDBOX.Test.TestModule(); //this throws the error

对于

var testModule = Y.SANDBOX.Test.TestModule; //this doesn't throw the error

至于实例化对象,它与普通的 Javascript 没有什么不同:

var f = function(){
    //This is the constructor
}
f.prototype.myfunction = function(){
    //this is a function
}

您也可以使用他们的基础对象来创建您自己的自定义对象。

var x = Y.Base.create('ClassIdentifier', |Base object to extend from|, [Extensions], {
    //content of the object, functions, etc
}, {
    ATTRS: {
        |attributes goes here|
    }
};
Y.namespace('mynamespcae').X = x;

然后你可以这样做:

var xInstance = new Y.mynamespace.X();

参见 http://yuilibrary.com/yui/docs/base/或更具体地用于创建:http://yuilibrary.com/yui/docs/base/#create

关于javascript - YUI3 对象和带有模块的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12644199/

相关文章:

javascript - angular2 - 使变量更具可变性

javascript - 我在DOM中看到了element,但是在页面上没有看到他。 WP插件Jet菜单

javascript - 某些文档中的 new "[,"意味着什么?

javascript - 在YUI3中,有没有办法将 "reset"模型转换为以前保存的值?

dom - YUI3 DOM 未定义?

javascript - YUI3 JavaScript : get CSS for placeholder text

JavaScript,生成器 - 当没有设置退出条件时, 'yield' 如何从循环中中断?

css - PIE.htc 不能在 IE8 中使用 YUI3

javascript - 将输入值检索到 formData 对象中