문제

With Underscore.js, we can use defaults() to apply default values to an object.

var defaultProperties = { flavor : "vanilla", sprinkles : "lots" };
var iceCream = {flavor : "chocolate"};
_.defaults(iceCream, defaultProperties);

But in Javascript, default values could be realized by using prototypes, too.

var defaultProperties = { flavor : "vanilla", sprinkles : "lots" };
var iceCream = Object.create(defaultProperties);
iceCream.flavor = "chocolate";

What is the advantage and use case of Underscore.js' defaults()?

도움이 되었습니까?

해결책

  1. Mostly availability.

    Object.create() is available in ES5-compatible browsers, while _.defaults() will function in older, ES3-based browsers (IE8, IE7, etc.).

  2. Also for objects you didn't create().

    If the object already exists, you can't count on being able to alter its [[Prototype]] after-the-fact to establish the desires inheritance.

    It's possible in some browsers, but not standard.

  3. It might make things easier with more than 1 defaults object.

    _.defaults(options, config, defaults);
    

    This is possible with prototype chains, but you have to establish one.

    var defaults = { /* ... */ };
    
    var config = Object.create(defaults);
    config.mixed = true;
    
    var iceCream = Object.create(config);
    iceCream.flavor = 'chocolate';
    

But, in general, they serve very similar purposes. They just do so from different perspectives:

  • _.default() iterates to find and set what's missing.
  • Object.create() uses prototype chains to inherit what's missing.

So, which to use is largely up to you and your personal preferences.

다른 팁

There is absolutely no difference except that using Underscore's defaults function saves you from writing extra code for validating and assigning a set of properties to the desired object. By abstracting that into a single function your code would look a bit more meaningful and neat. Which makes it a handy utility function.

Here is the source of Underscore's defaults function

// Fill in a given object with default properties.
  _.defaults = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      if (source) {
        for (var prop in source) {
          if (obj[prop] === void 0) obj[prop] = source[prop];
        }
      }
    });
    return obj;
  };

It takes the object and set of values as parameter, loops through the set of propeties and if the property doesn't already exist in that object, assign it to it. Source: UnderscoreJS code on Github

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top