JavaScript 是否按引用传递? [英] Does JavaScript pass by reference?

查看:17
本文介绍了JavaScript 是否按引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript 是按引用传递还是按值传递?

Does JavaScript pass by references or pass by values?

这是 JavaScript:优秀部分.我对矩形函数的 my 参数感到非常困惑.它实际上是undefined,并在函数内部重新定义.没有原始参考.如果我把它从函数参数中移除,则内部区域函数无法访问它.

Here is an example from JavaScript: The Good Parts. I am very confused about the my parameter for the rectangle function. It is actually undefined, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.

是闭包吗?但是没有返回任何函数.

Is it a closure? But no function is returned.

var shape = function (config) {
    var that = {};
    that.name = config.name || "";
    that.area = function () {
        return 0;
    };
    return that;
};

var rectangle = function (config, my) {
    my = my || {};
    my.l = config.length || 1;
    my.w = config.width || 1;
    var that = shape(config);
    that.area = function () {
        return my.l * my.w;
    };
    return that;
};

myShape = shape({
    name: "Unhnown"
});

myRec = rectangle({
    name: "Rectangle",
    length: 4,
    width: 6
});

console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area());

推荐答案

基元通过值传递,对象通过引用的副本"传递.

Primitives are passed by value, and Objects are passed by "copy of a reference".

具体来说,当您传递一个对象(或数组)时,您(不可见地)传递了对该对象的引用,并且可以修改该对象的内容,但是如果您尝试覆盖引用它不会影响调用者持有的引用副本 - 即引用本身是按值传递的:

Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:

function replace(ref) {
    ref = {};           // this code does _not_ affect the object passed
}

function update(ref) {
    ref.key = 'newvalue';  // this code _does_ affect the _contents_ of the object
}

var a = { key: 'value' };
replace(a);  // a still has its original value - it's unmodfied
update(a);   // the _contents_ of 'a' are changed

这篇关于JavaScript 是否按引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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