ES6中对象字面量中使用'this'的用法

6

我已经从事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 可以吗?

__location__对象中已经定义了属性_host和port。那么这个问题的意义是什么呢? - user5548116
1
@nAz - 这是一个关于node.js的问题,而不是浏览器问题(请看问题标签)。在node.js中没有location对象。 - jfriend00
@jfriend00 哦,我以为这是前端的问题。谢谢。 - user5548116
2个回答

13

你可以使用方法或获取器函数,两者都可以工作,但使用获取器函数会使属性与方法行为不同,在某些情况下可能很有用。

// 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


3

虽然不完全像你的方法,但你可以使用一个函数作为构造函数来创建具有此行为的对象:

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接