您现在的位置:首页 >> 前端 >> 内容

实现extend函数

时间:2017/6/19 9:35:53 点击:

  核心提示:浅拷贝使用Object.assign就够了,大多数情况下,使用该方法。深拷贝: (参考:zepto extend)var class2type = {}function type(obj) {retu...

浅拷贝使用Object.assign就够了,大多数情况下,使用该方法。

深拷贝: (参考:zepto extend)

var class2type = {}
function type(obj) {
  return obj == null ? String(obj) :
    class2type[toString.call(obj)] || "object"
}
function isFunction(value) { return type(value) == "function" }
function isWindow(obj)     { return obj != null && obj == obj.window }
function isDocument(obj)   { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
function isObject(obj)     { return type(obj) == "object" }
function isPlainObject(obj) {
  return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
var isArray = Array.isArray ||
    function(object){ return object instanceof Array }

function extend(target, source, deep) {
  for (key in source)
    if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
      if (isPlainObject(source[key]) && !isPlainObject(target[key]))
        target[key] = {}
      if (isArray(source[key]) && !isArray(target[key]))
        target[key] = []
      extend(target[key], source[key], deep)
    }
    else if (source[key] !== undefined) target[key] = source[key]
}

直接Clone一个Nested Object的简便方法:

var origin = {"a": "a"}
var copy = JSON.parse(JSON.stringify(origin));

Tags:实现 现E EX XT 
作者:网络 来源:初漾的博客