如何从另一个属性访问对象文字属性

How to access an object literal property from another property?

本文关键字:属性 访问 文字 对象 另一个      更新时间:2023-09-26

这可能非常简单,而且我的谷歌功能还不够强大。如果是复制品,我深表歉意。

考虑以下对象文字:

var config = {
    url: 'http://google.com',
    message: 'You must go to <a href="' + url + '">Google</a> to search!'
};

我得到一个错误,说url is not defined。如何从消息元素访问url元素?

我认为您可以包装config对象,例如

var config = (function() {
  var _url = 'http://google.com';
  return {
    url : _url,
    message : 'You must go to <a href="' + _url + '">Google</a> to search!'
  }
})();

你可以只做这个

var config = {
    url: 'http://google.com',
    message: function () { return 'You must go to <a href="' + this.url + '">Google</a> to search!' }
};

并致电

config.message();

以获取消息。