'这'ES6中的内部对象文字

Use of 'this' inside object literal in ES6

本文关键字:内部对象 文字 ES6      更新时间:2023-09-26

我做Node.js和前端Javascript的时间已经足够长了,所以我应该知道这个问题的答案。

假设我有一个像这样的对象文字:

       'lectal_api_server': {
            host: 'https://xyz.herokuapp.com',
            port:  process.env.PORT || 80,
            url:  'https://xyz.herokuapp.com:80'
        }

有可能做这样的事情吗:

      'lectal_api_server': {
            host: 'https://xyz.herokuapp.com',
            port:  process.env.PORT || 80,
            url:   this.host + ':' + this.port
         }

我不相信ES5可能会出现这种情况,但ES6可能吗?

您可以使用方法或getter函数。两者都会起作用,但getter函数会使属性表现为属性而不是方法,这在某些情况下可能很有用。

// As a method
lectal_api_server = {
  host: 'https://lectal-api.herokuapp.com',
  port: 80,
  getUrl: function() {
    return this.host + ':' + this.port
  }
}
console.log('%c As a method', 'font-weight: bold');
console.log(lectal_api_server.getUrl());
for (var key in lectal_api_server) {
  console.log(key, ':', lectal_api_server[key]);
}
console.log(JSON.stringify(lectal_api_server));
// Using a getter
lectal_api_server = {
  host: 'https://lectal-api.herokuapp.com',
  port: 80,
  get url() {
    return this.host + ':' + this.port
  }
}
console.log('%c Using a getter', 'font-weight: bold');
console.log(lectal_api_server.url);
for (var key in lectal_api_server) {
  console.log(key, ':', lectal_api_server[key]);
}
console.log(JSON.stringify(lectal_api_server));

请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

与您的方法不完全一样,但您可以使用函数作为构造函数来创建具有以下行为的对象:

var LectalApiServer = function( host, port ){
    this.host = host;
    this.port = port;
    this.url = this.host + ":" + this.port;
};
var myLectalApiServer = new LectalApiServer( "http://...", 80);
console.log(myLectalApiServer.url);