Last active
June 12, 2017 03:23
-
-
Save ifyour/9caad3445c6469eb64be884187fd29fa to your computer and use it in GitHub Desktop.
原生 JavaScript 实现一个 extends 扩展函数.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// about assign : | |
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign | |
// 对象的扩展, 本质上是一次复制操作, 将新增的属性或者方法 copy 到一个新的对象中 | |
var _extends = Object.assign || function(target) { | |
for (var i = 1; i < arguments.length; i++) { | |
var source = arguments[i]; | |
for (var key in source) { // 遍历传入的对象的属性 | |
if (Object.prototype.hasOwnProperty.call(source, key)) { // 只操作该实例上的属性和方法, 避免循环原型 | |
target[key] = source[key]; | |
} | |
} | |
} | |
return target; | |
}; | |
// ********************************************* | |
// Demo | |
// ********************************************* | |
var obj1 = { | |
a: 1, | |
b: 2, | |
c: 3 | |
}; | |
var obj2 = _extends({}, obj1, { | |
d: 4, | |
e: 5, | |
f: 6 | |
}); | |
console.log(obj2); | |
/* result : | |
{ | |
"a": 1, | |
"b": 2, | |
"c": 3, | |
"d": 4, | |
"e": 5, | |
"f": 6 | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment