在Github上查看CoffeeScript的源代码时,我注意到大多数(如果不是全部)模块定义如下:
(function() {
...
}).call(this);
Run Code Online (Sandbox Code Playgroud)
这种模式看起来像是将整个模块包装在匿名函数中并调用自身.
这种方法的优点和缺点是什么?还有其他方法可以实现相同的目标吗?
在不污染全局命名空间的情况下,在匿名函数之外获取变量的最佳做法是什么?
出于某种原因,coffeescript编译器在编译时将所有.coffee文件包装在函数中.例如,如果我有test.coffee:
class TestClass
constructor: (@value) ->
printValue: () ->
alert(@value)
printAValue = () ->
test = new TestClass()
test.printValue()
Run Code Online (Sandbox Code Playgroud)
然后我得到test.js:
(function() {
var TestClass, printAValue;
TestClass = (function() {
function TestClass(value) {
this.value = value;
}
TestClass.prototype.printValue = function() {
return alert(this.value);
};
return TestClass;
})();
printAValue = function() {
var test;
test = new TestClass();
return test.printValue();
};
}).call(this);
Run Code Online (Sandbox Code Playgroud)
我的简单html文件不适用于此:
<html>
<head>
<script src="test.js"></script>
</head>
<body onload="printAValue()">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我之前没有使用过很多JS,我不会怀疑咖啡编译器,但它应该如何工作?怎么样
我在使用CoffeeScript创建函数时遇到了一些麻烦,我想我错过了一些东西.对于我的用户控制器,我想为注册表单创建客户端验证.我想我已经错过了这一切如何运作的基本原则.
<%= form_for @user, :html => {:onsubmit => "return validate_signup_form();"} do |f| %>
Run Code Online (Sandbox Code Playgroud)
CoffeeScript(assets/users.js.coffee):
validate_signup_form = () ->
alert "Hi"
return false
Run Code Online (Sandbox Code Playgroud)
预期产量:
var validate_signup_form;
validate_signup_form = function() {
alert("Hi");
return false;
};
validate_signup_form();
Run Code Online (Sandbox Code Playgroud)
实际输出:
(function() {
var validate_signup_form;
validate_signup_form = function() {
alert("Hi");
return false;
};
}).call(this);
Run Code Online (Sandbox Code Playgroud) buildIMG = (src, resize) ->
html = '<div class="left"><div class="foods_image">'
html += '<a onclick="popitup("http://somewhere.com/test" href="javascript:void(0)">'
html += ' <img src="'+src+'" '+resize+' />'
html += '</a>'
html += '</div></div>'
html
popitup = (url) ->
newwindow=window.open(url,'name','height=640,width=640')
newwindow.focus() if window.focus
false
Run Code Online (Sandbox Code Playgroud)
我目前有一个书签,可以将javascript代码(上面的代码)插入到网站中.我写了上面的coffeescript,它产生了这个:
(function() {
var buildIMG, popitup;
buildIMG = function(src, resize) {
var html, nbsp;
html = '<div class="left"><div class="foods_image">';
html += '<a onclick="popitup(\'http://somewhere.com/test\');" href="javascript:void(0)">';
html += ' <img src="' + src + '" ' + resize + ' />';
html += '</a>'; …Run Code Online (Sandbox Code Playgroud) funName = () ->
$(".foo").addClass("bar");
Run Code Online (Sandbox Code Playgroud)
编译成匿名函数的范围.funName从控制台调用会导致undefined.
(function() {
var funName;
funName = function() {
return $(".foo").addClass("bar");
};
}).call(this);
Run Code Online (Sandbox Code Playgroud)
这样编译的原因是什么?如何使用它?
此外,使用CoffeeScript对函数内强制返回的任何见解都会很棒.为什么会那样?我如何因为它而需要不同的代码?