我需要你的帮助。如何在命名空间中使用变量?如下所示:
$.MyScript = {
script: $("script")
, dataID: script.data("id")
, dataColor: script.data("color")
, Alerting: function alerting(){
alert(dataColor);
}
}
$.Myscript.Alerting;发布于 2013-03-03 17:53:41
首先,这不是编写jQuery插件的正确方式,如果你想这样做的话。请咨询jQuery's Plugins/Authoring docs以了解正确的方法。
除此之外,您现在拥有代码的方式可以通过使用关键字this引用父对象来访问dataColor。
我正在从我的答案中删除代码,因为您还有其他问题。查看@dfsq对您问题的解决方案的回答。
我只是在这里留下我的答案,作为对官方文档的参考。
发布于 2013-03-03 17:54:43
在创建对象之前,不能访问script属性。您可以改为使用此模式:
$.MyScript = (function() {
var $script = $("script");
return {
script: $script,
dataID: $script.data("id"),
dataColor: $script.data("color"),
alerting: function alerting() {
alert(this.dataColor);
}
}
})();
$.MyScript.alerting();发布于 2013-03-03 18:18:55
我建议您使用一种更通用的方法,而不涉及jQuery。您可以随时创建自己的名称空间,并对其进行扩展。
请阅读Addy Osmani的this beautiful article以了解更多详细信息。
/* define a global var, the root of your namespace */
var myNamespace = myNamespace || {};
/*
* init and populate your ns inside a immediately invoked function expression
* you can pass the jQuery object as argument if you need it in your business logic
* but it is not necessary
*/
(function(ns, $){
ns.ScriptObject = function($script){
var $s = $script;
this.getDataColor = function(){
return $s.data("color");
}
this.getDataId = function(){
return $s.data("id");
}
/* add further methods */
}
})(myNamespace ,jQuery)https://stackoverflow.com/questions/15184402
复制相似问题