How to copy an object and prototype chain without calling its constructor function?

How to copy an object and prototype chain without calling its constructor function?

In other words, what does the dup function look like in the following example?

 class Animal @sleep: -> console.log('sleep') wake: -> console.log('wake') end class Cat extends Animal constructor: -> super console.log('create') attack: -> console.log('attack') end cat = new Cat() #> create cat.constructor.sleep() #> sleep cat.wake() #> wake cat.attack() #> attack dup = (obj) -> # what magic would give me an effective copy without # calling the Cat constructor function again. cat2 = dup(cat) #> nothing is printed! cat2.constructor.sleep() #> sleep cat2.wake() #> wake cat2.attack() #> attack 

How painful it is for me to watch, here's a jsfiddle example.

I also need properties, despite using only functions in my example.

+4
source share
2 answers
 function dup(o) { return Object.create( Object.getPrototypeOf(o), Object.getOwnPropertyDescriptors(o) ); } 

Which depends on ES6 Object.getOwnPropertyDescriptors . You can imitate this. Taken from pd

 function getOwnPropertyDescriptors(object) { var keys = Object.getOwnPropertyNames(object), returnObj = {}; keys.forEach(getPropertyDescriptor); return returnObj; function getPropertyDescriptor(key) { var pd = Object.getOwnPropertyDescriptor(object, key); returnObj[key] = pd; } } Object.getOwnPropertyDescriptors = getOwnPropertyDescriptors; 

Living example

Converting this to a coffeescript file remains as an exercise for the user. Also note that dup small copies of your own properties.

+5
source

You must use the special __proto__ element, which is available for each object and is a pointer to the prototype of the object class. The following code is in pure javascript:

 function dup(o) { var c = {}; for (var p in o) { c[p] = o[p]; } c.__proto__ = o.__proto__; return c; } 
0
source

Source: https://habr.com/ru/post/1387083/


All Articles