JAVASCRIPT - Why isn't this object changed?

2019-07-16 05:17发布

function myFunc(theObject) {  
  theObject = {make: "Ford", model: "Focus", year: 2006};  
}  
var mycar = {make: "Honda", model: "Accord", year: 1998};  
var x = mycar.make;     // returns Honda  
myFunc(mycar);  
var y = mycar.make;     // still returns Honda  

Why doesn't myFunc change the mycar object??

4条回答
淡お忘
2楼-- · 2019-07-16 05:25

When you do theObject = { ... } within myFunc, you are creating a new object and assigning its reference to the local variable theObject. This does not change the original object.

To modify the contents of the original object, you need to directly modify its properties like this:

theObject.make = 'Ford';
theObject.model = 'Focus';
theObject.year = 2006;
查看更多
地球回转人心会变
3楼-- · 2019-07-16 05:28

The question is already answered, just to make it even clearer:

function myFunc(theObject) {  
      theObject = {make: "Ford", model: "Focus", year: 2006};  
} 

is something similar (forget the syntax, get the message) to:

function myFunc(theObject) {  
      theObject = new TheObject("Ford","Focus",2006);  
} 

in other words, the parameter is referenced but you are changing that reference by constructing a new object.

Note: Since Java syntax is so popular I thought of using a JAVA-like syntax in order to explain, with didactic purposes, that you're creating a whole new instance. "TheObject" would be the name of the class.

查看更多
我想做一个坏孩纸
4楼-- · 2019-07-16 05:41

Javascript is modifying the local reference not the original reference when making the change you supplied. This post on SO should help:

Is JavaScript a pass-by-reference or pass-by-value language?

查看更多
\"骚年 ilove
5楼-- · 2019-07-16 05:47

Change this:

function myFunc(theObject) {  
      theObject = {make: "Ford", model: "Focus", year: 2006};  
    } 

Here you are reassigning your variable to a new object. The original is left unchanged, because parameter does not link to the variable holding the object.

to:

function myFunc(theObject) {  
  theObject.make = "Ford";
} 

This changes the object's properties you passed in.

查看更多
登录 后发表回答