Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中访问子对象中的属性_Javascript_Javascript Objects - Fatal编程技术网

在javascript中访问子对象中的属性

在javascript中访问子对象中的属性,javascript,javascript-objects,Javascript,Javascript Objects,我用小提琴写了一个简单的测试脚本: 我要做的是将margin属性设置为2,并让obj.foptions.labelMargin和obj.marginClone接受这个值 我知道可以直接在obj.foptions.labelMargin和obj.marginlone中更改值。但这不允许我“改变一个地方,改变所有地方” 相反,obj.fooptions.labelMargin和obj.marginClone都是未定义的 如何将此.margin读取为2 代码: 在JavaScript中实现这一点的典型

我用小提琴写了一个简单的测试脚本:

我要做的是将margin属性设置为2,并让
obj.foptions.labelMargin
obj.marginClone
接受这个值

我知道可以直接在
obj.foptions.labelMargin
obj.marginlone
中更改值。但这不允许我“改变一个地方,改变所有地方”

相反,
obj.fooptions.labelMargin
obj.marginClone
都是
未定义的

如何将
此.margin
读取为2

代码:


在JavaScript中实现这一点的典型方法是使用函数创建保存状态的作用域。以下是以这种风格重写的代码:

function obj()
{
    var that = this;

    that.margin = 10;
    that.setMargin = function(val) { 
        that.margin = val; 
    };
    that.foptions = { 
        labelMargin: that.margin 
    };
    that.marginClone = that.margin;
}

var inst = new obj();
inst.setMargin(2);
console.dir(inst.foptions);
console.log(inst.marginClone);
console.log(inst.margin);


关于marginClone,回想一下JavaScript仅对对象类型具有引用语义——因此对于标量值,您将始终进行复制。如果希望通过引用传递标量,可以将标量包装在对象中

这个
不是那样工作的。你不能那样做。啊,我明白了。谢谢你的链接和提示。不需要
闭包,也不需要将继承与
一起使用。这里确实不需要
。我习惯性地使用它,因为您不能依赖于将
这个
设置为实例(例如,当从事件处理程序调用该方法时),并且始终使用闭包比确定将来可能从事件处理程序调用什么更容易。@Jonathan感谢您的解决方案。但是当我运行代码时,它将
inst.foptions.labelMargin
inst.marginClone
显示为10。我假设它应该由
inst.setMargin(2)
设置为2?在本例中,setMargin仅更改
margin
,而不是
marginClone
,因为没有代码保持这些内容同步。如果要保持这些同步,可以通过创建
margin
作为对象(以获取引用语义),或者在
setMargin
内部设置
marginClone
来实现。
function obj()
{
    var that = this;

    that.margin = 10;
    that.setMargin = function(val) { 
        that.margin = val; 
    };
    that.foptions = { 
        labelMargin: that.margin 
    };
    that.marginClone = that.margin;
}

var inst = new obj();
inst.setMargin(2);
console.dir(inst.foptions);
console.log(inst.marginClone);
console.log(inst.margin);