在声明对象时访问属性? [英] Access properties while declaring object?

查看:61
本文介绍了在声明对象时访问属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从当前值的父级访问值,但没有成功。我有以下2个示例javascript代码来演示我的问题:

I'm trying to access a value from the current value's parent but without success. I have these 2 sample javascript codes to demonstrate my issue:

1)

var x = {
    y : {
        a : "a",
        ab : this.a + "b"
    }
};

console.log(xy);

console.log(x.y);

> Object {
    a : a,
    ab : undefinedb
}






2)

var x = {
    y : {
        a : "a",
        ab : x.y.a + "b"
    }
};

console.log(x.y); // Uncaught TypeError: Cannot read property 'y' of undefined 


推荐答案

xy 未定义,因为此时它们是 undefined 。我的意思是,当你创建一个匿名对象时,它在关闭} 之前并不存在。

x.y and this are undefined as at that point they are undefined. What I mean is that when you create an anonymous object it does not really exist until the closing }.

所以实现你想要的另一种方式是:

So another way to achieve what you want would be:

var x = {
     y : {a : "a"}
}

x.y.ab = x.y.a + "b"

这样, ab 变量在 x y 已经初始化了,因此现在设置了 xya

This way the ab variable is being set after x and y have both been initialised, and therefore x.y.a is now set.

如果你真的想在期间设置xyab初始化然后你需要更正式地使用函数和闭包。类似于以下内容。

If you really want to set x.y.ab during initialisation then you would need to do it more formally with functions and closures. Something like the following.

var x = function(){
  this.a = 'foo';
  this.b = this.a + ' bar';
}() // Immediate function call so I don't have to create it.

console.log(x.b); // logs 'foo bar'

这篇关于在声明对象时访问属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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