JAVASCRIPT - 为什么这个对象没有改变? [英] JAVASCRIPT - Why isn't this object changed?

查看:54
本文介绍了JAVASCRIPT - 为什么这个对象没有改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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  

为什么 myFunc 不改变 mycar 对象??

Why doesn't myFunc change the mycar object??

推荐答案

问题已经回答了,只是为了更清楚:

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.

注意:由于 Java 语法如此流行,我想使用类似 JAVA 的语法来解释,出于教学目的,您正在创建一个全新的实例.TheObject"将是类的名称.

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.

这篇关于JAVASCRIPT - 为什么这个对象没有改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆