【发布时间】:2016-04-15 19:18:21
【问题描述】:
注意:我正在使用 Babel 作为我的转译器
我正在尝试用一些私有方法的概念来实现一个 ES6 类。为此,我在类声明之外声明了一个函数,并且我还尝试将闭包用于 DRY 实践。
但是,当我的类方法调用“私有”方法时,this 的上下文变得未定义。我认为使用 bind() 应该显式设置上下文,但它似乎不起作用。
function _invokeHttpService(httpMethod) {
return (url, config, retries, promise) => {
var s = this;
// Do some additional logic here...
httpMethod(url, config)
.then(
response => {
s._$log.info(`Successful response for URL: ${url}`);
promise.resolve(response);
},
error => {
s._$log.error(`Request for URL: ${url} failed.`);
promise.reject(error)
});
}
}
function _get(url, config, retries, promise) {
_invokeHttpService(this._$http.get);
}
class httpSessionService {
/*@ngInject*/
constructor($log, $http, $q, $timeout, CODE_CONSTANTS, $rootScope) {
this._$log = $log;
this._$http = $http;
this._$q = $q;
this._$timeout = $timeout;
this._$rootScope = $rootScope;
this._CODE_CONSTANTS = CODE_CONSTANTS;
}
get(url, config, retries = 5) {
var s = this;
var deferred = s._$q.defer();
_get(url, config, retries, deferred).bind(this);
return deferred.promise;
}
}
【问题讨论】:
标签: javascript angularjs closures ecmascript-6