ホームページ >ウェブフロントエンド >jsチュートリアル >jQuery.extend()実装_javascriptスキルの詳しい説明と例
浅いコピーの実装
浅いコピーのみを実装する必要がある場合は、次のようなものを使用できます。
ディープコピーの実装
「ディープコピー」を実装したい場合、コピーされたオブジェクトが配列またはオブジェクトの場合、extendを再帰的に呼び出す必要があります。次のコードは、「ディープ コピー」の単純な実装です:
コードをコピーします
より完全な実装
次の実装は jQuery の extend() に近くなります:
class2type = {
'[オブジェクト ブール値]' : 'ブール値',
'[オブジェクト番号]' : '数値',
'[オブジェクト文字列]' : '文字列',
'[オブジェクト関数]' : '関数',
'[オブジェクト配列]' : '配列',
'[オブジェクト日付]' : '日付',
'[オブジェクト正規表現]' : 'regExp',
'[オブジェクト オブジェクト]' : 'オブジェクト'
},
type = function(obj) {
return obj == null ?文字列(obj) : class2type[toString.call(obj)] || "オブジェクト";
},
isWindow = function(obj) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isArray = Array.isArray || function(obj) {
return type(obj) === "配列";
},
isPlainObject = function(obj) {
if (!obj || type(obj) !== "object" || obj.nodeType || isWindow(obj)) {
return false;
}
if (obj.constructor && !hasOwn.call(obj, "constructor")
&& !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
var key;
for (obj のキー) {
}
リターンキー === 未定義 || hasOwn.call(obj, key);
},
extend = function(deep, target, options) {
for (オプションの名前) {
src = target[name];
copy = options[name];
if (ターゲット === コピー) { 続行; }
if (ディープ && copy
&& (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
クローン = src && isArray(src) ?ソース: [];
} else {
clone = src && isPlainObject(src) ?ソース: {};
}
target[name] = extend(deep, clone, copy);
} else if (copy !== 未定義) {
target[name] = copy;
}
}
ターゲットを返す;
};
return { extend : extend };
}();
次に、オブジェクトが配列であるかどうかを判断する方法:
最後に、isPlainObject の実装を文ごとに見てみましょう: