有没有相当于Ruby的Javascript和?

Jam*_*sen 5 javascript ruby andand

在试图使我的Javascript不引人注目时,我正在使用onLoads来为<input>s等添加功能.使用Dojo,这看起来像:

var coolInput = dojo.byId('cool_input');
if(coolInput) {
  dojo.addOnLoad(function() {
    coolInput.onkeyup = function() { ... };
  });
}
Run Code Online (Sandbox Code Playgroud)

或者,大致相当于:

dojo.addOnLoad(function() {
  dojo.forEach(dojo.query('#cool_input'), function(elt) {
    elt.onkeyup = function() { ... };
  });
});
Run Code Online (Sandbox Code Playgroud)

有没有人写Ruby的的实现andand,这样我可以做到以下几点?

dojo.addOnLoad(function() {
  // the input's onkeyup is set iff the input exists
  dojo.byId('cool_input').andand().onkeyup = function() { ... };
});
Run Code Online (Sandbox Code Playgroud)

要么

dojo.byId('cool_input').andand(function(elt) {
  // this function gets called with elt = the input iff it exists
  dojo.addOnLoad(function() {
    elt.onkeyup = function() { ... };
  });
});
Run Code Online (Sandbox Code Playgroud)

har*_*333 2

您想要的确切语法在 JavaScript 中是不可能的。JavaScript 的执行方式需要从根本上进行改变。例如:

var name = getUserById(id).andand().name;
//                        ^
//                        |-------------------------------
// if getUserById returns null, execution MUST stop here |
// otherwise, you'll get a "null is not an object" exception
Run Code Online (Sandbox Code Playgroud)

然而,JavaScript 并不是这样工作的。事实并非如此。

以下行几乎完全符合您的要求。

var name = (var user = getUserById(id)) ? user.name : null;
Run Code Online (Sandbox Code Playgroud)

但可读性不会扩展到更大的例子。例如:

// this is what you want to see
var initial = getUserById(id).andand().name.andand()[0];
// this is the best that JavaScript can do
var initial = (var name = (var user = getUserById(id)) ? user.name : null) ? name[0] : null;
Run Code Online (Sandbox Code Playgroud)

这些不必要的变量会产生副作用。我使用这些变量来避免双重查找。这些变量会破坏上下文,如果这是一个大问题,您可以使用匿名函数:

var name = (function() {return (var user = getUserById(id)) ? user.name : null;})();
Run Code Online (Sandbox Code Playgroud)

现在,用户变量已正确清理,每个人都很高兴。但是哇!打字量真大啊!:)

  • 或者使用 [CoffeeScript](http://jashkenas.github.com/coffee-script/#operators):查看“存在运算符的访问器变体”`?.` :) (3认同)