我在另一个对象中有一个对象,我需要访问第一个父对象的属性。这是我的代码。
var api = {
apiBaseUrl: 'http://example.com/',
sendRequest: function (url, method, data) {
console.log('send request')
$.ajax({
url: 'url',
type: method,
data: data
})
},
/**
* string topic, function callback
*/
study: {
getStudies: function () {
var url = this.apiBaseUrl + 'studies';
var method = 'GET';
this.sendRequest(url, method);
},
};
};
api.study.getStudies()
在函数 api.study.getStudies()
中,我想访问变量 apiBaseUrl
和 的函数
对象,我该怎么做?sendRequest
>api
最佳答案
对于您引用的内容,您只有一个对象,因此只需在您当前拥有 this
的地方使用 api
。由于函数是包含 api
变量的上下文的闭包,因此它们可以访问该变量。
请注意,引用的代码也有语法错误。
所以变化是:
study: {
getStudies: function () {
var url = api.apiBaseUrl + 'studies'; // <== Here
var method = 'GET';
api.sendRequest(url, method); // <== Here
},
} // <== Here (the ; was a syntax error)
关于Javascript - 对象访问第一个父属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23873691/