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

我一直在做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函数将使属性performance为属性而不是方法,在某些情况下可能会有用。

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

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

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