4

I need something like Ext.apply in Node.js. The most obvious way is to define my own:

function simplestApply(dst, src1) {
  for (var key in src) if (src.hasOwnProperty(key))
    Object.defineProperty(dst, key, Object.getOwnPropertyDescriptor(src, key));
}

But isn't there any built-in function for the same purpose?

Pavel Koryagin
  • 1,479
  • 1
  • 13
  • 27
  • `Function.apply` ? its build-it in V8, and thus in Node. – c69 Sep 23 '11 at 11:08
  • No. Function's apply() is quite different thing for different purpose, than Ext.apply() and simplestApply() above. – Pavel Koryagin Sep 23 '11 at 13:35
  • 1
    ah, you want something like `merge` ? - then no, there is nothing like that in vanilla js. http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically or `jQuery.extend()` or `Object.append()` (MooTools). – c69 Sep 23 '11 at 13:45
  • Thanks. I just found built-in features for some framework-powered utils, like `bind`. I thought it could be something for merge|extend|append|apply too. – Pavel Koryagin Sep 23 '11 at 14:19

1 Answers1

1

This is the fastest way, but it doesn't copy the functions.

JSON.parse(JSON.stringify(obj))
Pavel Koryagin
  • 1,479
  • 1
  • 13
  • 27
Farid Nouri Neshat
  • 29,438
  • 6
  • 74
  • 115
  • This method does not apply properties to an existent object. It is a way to clone JSON-like tree. But it is fast, that's true. About 3 times faster than `simplestApply({}, obj)` according my tests. – Pavel Koryagin Sep 28 '11 at 16:43
  • You can do this, too. `var b = {}; for (var i in a) { b[i] = a[i]; }` It is faster: http://jsperf.com/object-copying – Farid Nouri Neshat Oct 11 '11 at 09:04