Javascript:不同的返回类型 [英] Javascript: Different return types

查看:70
本文介绍了Javascript:不同的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到我可以在JavaScript中从同一个函数返回不同的类型。这种做法是惯用还是不鼓励?

I saw I could return different types from the same function in JavaScript. Is this practice idiomatic or should it be discouraged?

例如:

somefn = function(e) {
    switch (e.type) 
    {
       case 'mousedown':
         return false;
       case 'mousemove':
         return {x:10, y:20};
    }
 };


推荐答案

请注意,不仅你的函数返回不同的类型,但甚至可能不会返回任何内容:

Please note that not only your function returns different types, but might even not return anything:

somefn({type: 'foo'});  //undefined

虽然不鼓励上述不一致的返回行为,但返回不同的对象类型很常见,虽然我不能说它是不是惯用的。

Although inconsistent return behavior described above is discouraged, returning different object types is common, although I can't say if it is idiomatic.

为了便于阅读和维护,我不建议返回完全不同的对象(比如boolean)和示例中的对象文字一样,但返回具有稍微甚至完全不同属性的对象文字是很常见的:

For the sake of readability and maintainability I wouldn't recommend returning completely different objects (like boolean and object literal in your example), but returning object literals with just slightly or even completely different properties is pretty common:

somefn = function(e) {

  switch (e.type) 
  {
    case 'mousedown':
      return {x:10, y:20, down: false};
    case 'mousemove':
      return {x:10, y:20};
    default:
      return {};
  }
};

这篇关于Javascript:不同的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆