我需要你的帮助。如何在命名空间中使用变量?像这样的东西:
$.MyScript = {
    script: $("script")
  , dataID: script.data("id")
  , dataColor: script.data("color")
  , Alerting: function alerting(){
        alert(dataColor);
    }
}
$.Myscript.Alerting;
我需要你的帮助。如何在命名空间中使用变量?像这样的东西:
$.MyScript = {
    script: $("script")
  , dataID: script.data("id")
  , dataColor: script.data("color")
  , Alerting: function alerting(){
        alert(dataColor);
    }
}
$.Myscript.Alerting;
首先,这不是编写 jQuery 插件的正确方法,如果这就是您想要做的。咨询jQuery 的插件/创作文档以了解正确的方法。
除此之外,您现在拥有代码的方式可以dataColor通过使用关键字引用父对象来访问this。
我正在从我的答案中删除代码,因为您还有其他问题。查看@dfsq 的答案以解决您的问题。
我只是在这里留下我的答案作为对官方文档的参考。
在创建对象之前,您无法访问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();
我建议您使用更通用的方法,而不涉及 jQuery。您始终可以创建自己的命名空间并对其进行扩展。
阅读Addy Osmani 的这篇漂亮文章,了解更多详情。
/* 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)