我找到了这个用于 jQuery 插件的 CoffeeScript 样板,我一直在研究并[试图]在我[试图]编写的插件中使用它。我在其他几个问题中引用了相同的样板/模板。我是 JavaScript 的业余爱好者,也是 CoffeeScript 的新手。我正在努力学习和学习,但是当有些事情困扰我并且我无法通过 Google 找到令人满意的答案时,我来到这里......所以请原谅我在此处编写和呈现的任何代码中缺乏知识和潜在错误.
CoffeeScript 代码编译为:
(function() {
(function($, window, document) {
var $this, methods, _anotherState, _flag, _internals, _settings;
$this = void 0;
_settings = {
"default": 'cool!'
};
_flag = false;
_anotherState = null;
methods = {
init: function(options) {
$this = $(this);
$.extend(_settings, options || {});
return $this;
},
doSomething: function(what) {
return $this;
},
destroy: function() {
return $this;
}
};
_internals = {
toggleFlag: function() {
return _flag = !_flag;
},
computeSomething: function(state, flag) {
return flag != null ? flag : {
state: "No, that's not right."
};
}
};
return $.fn.foobar = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
return methods.init.apply(this, arguments);
} else {
return $.error("Method " + method + " does not exist on jquery.foobar");
}
};
})(jQuery, window, document);
}).call(this);
从这里和这里我了解到,(function(){...}).call(this)
包装器是 CoffeeScript 的一项功能,旨在本地化未明确声明为全局的变量。后来我才知道它也可以在编译过程中被抑制。我还了解到我不需要包含window
和document
作为 jQuery 闭包的参数。
当我更多地研究它(并尝试编辑它)时,我看到在编译的代码中,闭包(它是一个函数)$.fn.foobar
在它定义它的地方返回。由于该函数是匿名的并且无论如何都不会被调用,我想返回的值并不重要。但是,如果我return
在 CoffeeScript 代码中添加这样的语句会怎样:
$.fn.foobar = (method) ->
if methods[method]
methods[method].apply this, Array::slice.call(arguments, 1)
else if typeof method is "object" or not method
methods.init.apply this, arguments
else
$.error "Method " + method + " does not exist on jquery.foobar"
# -- This, right here...
return
# --
return $.fn.foobar = ...
它不再编译为$.fn.foobar = ...
. 我认为这没有任何区别,而是使 JS 输出更...干净...如果您愿意的话。但我需要确认这一点。这对脚本的执行有何影响?
此外,在 CoffeeScript 代码中,作者说methods.init()
我需要在里面执行所有操作,$this.each
但是,如果我这样做
init: (options) ->
$.extend _settings, (options or {})
return $(@).each () -> # I don't really need return, do I?
# In here @ is one element (out of the array of elements)
return # This is to suppress any returns inside .each()
所以就是这样......这是我的问题:
- 是否有理由不
return
使用 CoffeeScript 代码中的匿名函数?这与原始 CoffeeScript 代码有何不同? - 什么是迭代调用插件的jQuery数组中所有项目的正确方法,同时保持可链接性。
注意:我没有包含 CoffeeScript 代码以避免帖子太长。但是我提供了一个链接到列出代码的页面。但是,如果有问题,请在评论中告诉我,我也会编辑帖子以包含 CoffeeScipt 代码。感谢您的时间。