Javascript将对象传递给函数 [英] Javascript passing object to function

查看:74
本文介绍了Javascript将对象传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Javascript的快速问题,我找不到一个简明的答案。

Quick question on Javascript to which I can't find a clear concise answer.

我正在构建的应用程序比我之前做过的任何事情都要先进并涉及多个实例化的类。然后将这些对象传递到处理类中,该处理类检查用户输入,在画布上绘制并更新已传递的对象。

I'm building an app that's way ahead of anything I've done before and involves multiple classes being instantiated. These objects are then passed into a processing class that checks user inputs, draws onto canvas and updates the objects that it has been passed.

我想知道JavaScript如何处理将对象传递给函数?我是传递对象的副本,还是传递对对象的引用?

I am wondering, how does JavaScript handle passing objects to functions? Am I passing a copy of the object, or am I passing a reference to the object?

因此,如果我的控制器类更改了对象变量之一,那么该变量是否到处改变了?还是只是在那个控制器看到的对象中?

So if my controller class alters one of the objects variables, is that changed everywhere or just in the object that that controller sees?

抱歉,这么简单,可能容易测试的问题,但是我什至不确定我是否正确地制作了一个类

Sorry for such a simple, possibly easily testable question but I'm not even sure if I'm making a class correctly at this point thanks to errors piling up.

推荐答案

传入基本类型变量(如字符串或数字)时,该值通过按值传递。这意味着在函数中对该变量所做的任何更改都与在函数外部发生的一切完全分开。

When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function.

function myfunction(x)
{
      // x is equal to 4
      x = 5;
      // x is now equal to 5
}

var x = 4;
alert(x); // x is equal to 4
myfunction(x); 
alert(x); // x is still equal to 4

传递对象,但是以传递通过引用。在这种情况下,该对象的任何属性都可以在函数中访问

Passing in an object, however, passes it in by reference. In this case, any property of that object is accessible within the function

function myobject()
{
    this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
    fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6

这篇关于Javascript将对象传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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