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

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -