'这'ES6中的内部对象文字
Use of 'this' inside object literal in ES6
我做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);
相关文章:
- 如何使用内部对象构造对象
- 如何计算对象文字中的键
- 对象文字方法上的Javascript绑定不起作用
- 可以使用“;创建“;作为JavaScript对象文字中的属性名称
- 这两种不同的创建对象文字的方法有什么区别
- Javascript对象文字,POST问题
- 为什么可以'我们在函数体中为函数对象添加属性,就像在javascript中为对象文字添加属性一样
- 如何使用'这个“;对象文字中的关键字
- JS对象文字中的方法和子方法
- 向JavaScript对象文字添加数据
- Javascript对象文字,如何使用“this”来引用对象中的变量
- 如何将xml文件转换为javascript中的对象文字
- 什么's对象文字中带引号和不带引号的键之间的区别
- 使用窗口对象练习我的对象文字函数
- 为什么这个内部对象文字等于另一个对象
- 如何在不位于javascript函数内部的情况下使用对象文字的属性
- '这'ES6中的内部对象文字
- 从回调(异步方法)内部访问对象文字属性
- 为什么可以't我从对象文字内部引用对象文字
- 如何获得一个内部对象文字值与javascript