javascript - Clone object with function -


i wanted clone original object , function without reference, code consider correct way clone object , function?

var apple = new function() {     this.type = "macintosh";     this.color = "red"; }   function aaa() {         return this.color + ' ' + this.type + ' apple';     };  var = json.parse(json.stringify(apple)) var b =  json.parse(json.stringify(apple));  console.log(a)   a.getinfo = aaa  b.getinfo = aaa  a.color='green' // green color  console.log(a.getinfo())  console.log(b.getinfo()) 

for cloning objects, can use object.assign , set first argument empty object. example

const clone = object.assign({}, apple.call({})); const result = aaa.call(clone); console.log(result); //=> red macintosh apple; 

i made use of function.call here because don't know if meant access global this or different scope or what. if do know this referring to, can do.

const clone = object.assign({}, this); const result = aaa(); console.log(result); 

mdn object.assign

mdn function.call


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -