简体   繁体   中英

How to access an object literal property from another property?

This is probably incredibly simple and my Google-fu is just not strong enough. My apologies if it is a duplicate.

Consider the following object literal:

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

I get an error saying that url is not defined . How do I access the url element from the message element?

I think you can wrap the config object, eg

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

You may just do this

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

And call

config.message();

to get the message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM