栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript按引用还是按值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript按引用还是按值

我的理解是,这实际上非常简单:

  • Javascript 总是 按值传递,但是当变量引用对象(包括数组)时,“值”是对对象的引用。
  • 更改变量的值 永远不会 更改基础原语或对象,而只是将变量指向新的原语或对象。
  • 但是,更改变量引用的对象的 属性 确实会更改基础对象。

因此,通过一些示例:

function f(a,b,c) {    // Argument a is re-assigned to a new value.    // The object or primitive referenced by the original a is unchanged.    a = 3;    // Calling b.push changes its properties - it adds    // a new property b[b.length] with the value "foo".    // So the object referenced by b has been changed.    b.push("foo");    // The "first" property of argument c has been changed.    // So the object referenced by c has been changed (unless c is a primitive)    c.first = false;}var x = 4;var y = ["eeny", "miny", "mo"];var z = {first: true};f(x,y,z);console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false

范例2:

var a = ["1", "2", {foo:"bar"}];var b = a[1]; // b is now "2";var c = a[2]; // c now references {foo:"bar"}a[1] = "4";   // a is now ["1", "4", {foo:"bar"}]; b still has the value   // it had at the time of assignmenta[2] = "5";   // a is now ["1", "4", "5"]; c still has the value   // it had at the time of assignment, i.e. a reference to   // the object {foo:"bar"}console.log(b, c.foo); // "2" "bar"


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/375652.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号