javascript - Why can we modify an object with a function argument, but we cannot redefine an object the same way? -


this question has answer here:

example code:

var person = {   name: 'sam',   age: 45 };  // function able modify name property function namechanger (obj, name) {   obj.name = name; }  namechanger(person, 'joe');  // modifies original object 

but trying redefine objection in similar function doesn't work @ all:

var person2 = {   name: 'ashley',   age: 26 };  function personredefiner (obj, name, age) {   obj = {     name: name,     age: age   }; }  personredefiner (person2, 'joe', 21); // original object not changed 

this second example not modify original object. have change function return object, set person2 = personredefiner(person2, 'joe', 21);

why first example work second example not?

in second example, you're initializing new object scope local function.


Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -