【Underscore.js】_.extendと_.extendOwnを読んだ
jashkenas/underscoreの_.extendと_.extendOwnを読んだ。
概要
_.extend(destination, *sources) _.extendOwn(destination, *sources)
- extend: sourcesに含まれている全てのプロパティ(プロトタイプを含む。)をdestinationにコピーしたものを返す
- extendOwn: sourcesに含まれている全てのプロパティ(プロトタイプは除く)をdestinationにコピーしたものを返す
var Hoge = function(){}; Hoge.prototype.own = false; var a = _.extend({}, {own: true}, new Hoge()); console.log(a); // {own: false} var b = _.extendOwn({}, {own: true}, new Hoge()); console.log(b); // {own: true}
ソースコード
_.extend = createAssigner(_.allKeys); _.extendOwn = _.assign = createAssigner(_.keys); var createAssigner = function(keysFunc, undefinedOnly) { return function(obj) { var length = arguments.length; if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; };
.allKeysでは、自身のプロトタイプのプロパティのkeyまで取得でき、.keysでは自身が持っているプロパティのkeyのみを取得できる。