0

I just tried something simple in javascript

name = 'velu' 
fname = name
name = 'valu'
console.log(fname) // would still print as velu...

how do you handle situation where you generated objects prototype is changed and the generated object still has a copy of the old object..

Here is the situation ...

function Cat(name){  
this.name = name  
}
var garfield = new Cat('Garfield')
Cat.prototype.greet = function(){
console.log('Meow, I am ' + this.name)
}
function Animal(){}
Cat.prototype = new Animal
Cat.prototype.constructor = Cat 
Animal.prototype.breed = function(){
console.log('Making a new animal!')
return new this.constructor()
}
 var kitty = garfield.breed() // this will not work as it garfield still is pointing to the old prototype object of Cat ...

thanks

coool
  • 8,085
  • 12
  • 60
  • 80
  • 2
    Don't leave out semi colons in JavaScript. – zzzzBov Sep 21 '12 at 18:36
  • 1
    Simple/primitive values will always be copied by value, rather than reference. Hence fname = 'velu'. Passing in an object, however, passes it in by reference. This may help: http://stackoverflow.com/questions/728360/copying-an-object-in-javascript – AlexP Sep 21 '12 at 18:39

1 Answers1

3

You'd have to make an object, which is passed around by reference:

var name = { Value: 'velu' };
var fname = name;
name.Value = 'valu';
console.log(fname.Value);
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326