amatiasq
4/30/2013 - 10:33 PM

Creates a copy of a object duplicating every property, even prototyped ones.

Creates a copy of a object duplicating every property, even prototyped ones.

var extend = Object.getOwnPropertyNames ?
  function ecma5extend(obj) {
    var proto = obj;
    var protos = [];
  	var result = {};
  	var descriptors = {};
  
  	while (proto) {
  		protos.push(proto);
  		proto = Object.getPrototypeOf(proto);
  	}
  
  	protos.reverse().forEach(function(ancestor) {
  		Object.getOwnPropertyNames(ancestor).forEach(function(prop) {
  			descriptors[prop] = Object.getOwnPropertyDescriptor(ancestor, prop);
  		});
  	});
  
    Object.defineProperties(result, descriptors);
  	return result;
  } :
  function fallback(obj) {
    var result = {};
    for (var i in obj)
      result[i] = obj[i];
    return result;
  };