本文介绍了Javascript对象如何引用值本身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下javascript:
Lets say I have the following javascript:
var obj = {
key1 : "it ",
key2 : key1 + " works!"
};
alert(obj.key2);
key1未定义时出现此错误。我试过了
This errors with "key1 is not defined". I have tried
this.key1
this[key1]
obj.key1
obj[key1]
this["key1"]
obj["key1"]
并且它们似乎永远不会被定义。
and they never seem to be defined.
如何让key2引用key1的值?
How can I get key2 to refer to key1's value?
推荐答案
也许您可以考虑将属性移除到函数中。我的意思是这样的:
Maybe you can think about removing the attribute to a function. I mean something like this:
var obj = {
key1 : "it ",
key2 : function() {return this.key1 + " works!";}
};
alert(obj.key2());
这篇关于Javascript对象如何引用值本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!