Guest User

Untitled

a guest
Jan 21st, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. var proto = Object.getPrototypeOf
  2. , keys = Object.keys
  3. , class_of = {}.toString
  4. , arrayp = Array.isArray
  5.  
  6. function objp(object) {
  7. return class_of.call(object) == '[object Object]'
  8. }
  9.  
  10. function copy_array(object, deep) {
  11. return object.map(function(value) {
  12. return copy(value, deep) })
  13. }
  14.  
  15. function copy_obj(object) { var result
  16. result = Object.create(proto(object))
  17. keys(object).forEach(function(key) {
  18. result[key] = copy(object[key], true) })
  19.  
  20. return result
  21. }
  22.  
  23. function copy(object, deep) {
  24. return arrayp(object)? copy_array(object, deep)
  25. : objp(object)? copy_obj (object, deep)
  26. : /* by value */ object
  27. }
  28.  
  29. var x = {a:1, b:2}
  30. var y = Object.create(x); y.c = 3;
  31. var z = {x: x, y: y}
  32. var a = Object.create(z);
  33. a.list = [[1, 2], [3,[4,[5]]]]
  34.  
  35. var _ = copy(a, true)
  36. a.list[1][0] = 4
  37. console.log(_.list[1][0] === 3)
  38.  
  39. _ = copy(z, true)
  40. x.a = 2
  41. console.log(_.x.a === 1)
Add Comment
Please, Sign In to add comment