我无法理解如何在 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/