argumental在JavaScript基准不一致 [英] argumental reference inconsistency in javascript

查看:213
本文介绍了argumental在JavaScript基准不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在JS遇到的一个讨厌的问题。

I have recently encountered a nasty issue in JS.

让说,我们通过一个地图,对象的数组到函数f。

Let say we pass a map, an array of objects to a function f.

var o=[{a:0}];
function f(a){
    for(var i in a){
        if (a.hasOwnProperty(i)){
            a[i]=null;
        }
    }
    return a;
};
var outp=f(o);

alert(outp[0]+" === "+o[0]+" : "+(outp[0]===o[0]));

// here we expect loose equality, and equality in type, 
//furthermore it should identically equal as well, and we got right!

但是,我们不能传递一个对象的全部责任给一个函数作为参数,同样喜欢在功能模式 O =(函数(O){回复O})(),因为任何一种修改邻没有被引用!

But, we can not pass total responsibility of an object to a function as argument, same like in functional paradigm o=(function(o){return o})(), because any kind of modification to o is not referenced!

var o=[];
function ff(a){
    return (a=undefined);
};
var outp=ff(o);
alert(outp+" === "+o.constructor+" : "+(outp===o));
// here we expect true, but we got false!

为什么上述的基准损失
$ P $在第二个用例psumably不同referencce处理,
虽然在这两个情况下,功能得到了在0位置数组参数?

Why is the above described reference loss and presumably different referencce handling in the second use case, though in both case, functions got the array argument in the 0. position?

推荐答案

的Javascript总是流逝值参数,所以这是行不通的:

Javascript always passes arguments by value, so this won't work:

 function foo(x) {
    x = 100;
 }

 y = 5
 foo(y)
 y == 100 // nope

不过,这不会工作:

However this does work:

 function foo(x) {
    x.bar = 100;
 }

 y = {}
 foo(y)
 y.bar == 100 // yes

在第二个片段x被仍然按值传递的,但是这个很值是一个引用(指针)的对象。所以这是有可能在一个函数取消对它的引用并访问什么是内部的对象。

In the second snippet x is still passed by value, but this very value is a reference (pointer) to an object. So it's possible in a function to dereference it and access what's "inside" the object.

这篇关于argumental在JavaScript基准不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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