LoginSignup
1
1

More than 5 years have passed since last update.

underscoreコードリーディング(result)

Posted at

underscoreに詳しくないので、勉強半分でソースコードを読む。

利用するバージョン

underscore.js(v1.8.3)

resultとは

underscorejs.orgのresult

こんな説明。

_.result(object, property, [defaultValue])

If the value of the named property is a function then invoke it with the object as context; otherwise, return it.
If a default value is provided and the property doesn't exist or is undefined then the default will be returned.
If defaultValue is a function its result will be returned.

var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"
_.result(object, 'meat', 'ham');
=> "ham"

valueが関数の名前だった場合、その関数を利用してその結果を返します。そうでない場合、それを返します。
デフォルトの値が与えられていて、そのプロパティが存在しないもしくはundefinedだった場合は、デフォルトの値を返します。
defaultValueが関数なら、それを返します(?)

underscore.result

コード的にはこのあたり。


  // If the value of the named `property` is a function then invoke it with the
  // `object` as context; otherwise, return it.
  _.result = function(object, property, fallback) {
    var value = object == null ? void 0 : object[property];
    if (value === void 0) {
      value = fallback;
    }
    return _.isFunction(value) ? value.call(object) : value;
  };

引数はobject,property,fallbackの3つ。
変数valueにobjectがnullの場合はvoid 0(undefined)を、そうでない場合はobject[property]を入れる。
valueが void 0だった場合、valueにfallbackを代入する。
_.isFunctionにvalueを渡した結果が関数だった場合、objectを渡してvalueをcallしたものを返し、そうでない場合はvalueを返す。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1