Javascript ES6:尽管使用了bind(),但这是未定义的
注意:我正在为我的transpiler使用Babel 我试图用一些私有方法的概念实现一个ES6类。为了做到这一点,我在类声明之外声明了一个函数,并且我还试图利用闭包进行干式实践 但是,当我的类方法调用“private”方法时,这个的上下文变得未定义。我认为使用bind()应该显式地设置上下文,但它似乎不起作用Javascript ES6:尽管使用了bind(),但这是未定义的,javascript,angularjs,closures,ecmascript-6,Javascript,Angularjs,Closures,Ecmascript 6,注意:我正在为我的transpiler使用Babel 我试图用一些私有方法的概念实现一个ES6类。为了做到这一点,我在类声明之外声明了一个函数,并且我还试图利用闭包进行干式实践 但是,当我的类方法调用“private”方法时,这个的上下文变得未定义。我认为使用bind()应该显式地设置上下文,但它似乎不起作用 function _invokeHttpService(httpMethod) { return (url, config, retries, promise) => {
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;
}
}
创建函数的副本,并将此
设置为第一个参数
var f = _get.bind(this);
f(url, config, retries, deferred);
您想要使用的是基本上是bind
,但是该函数会立即被调用。第一个参数是this
的值,而下面的任何参数都将传递给正在调用的函数
_get.call(this, url, config, retries, deferred);
call
有一个被调用的姐妹函数,该函数执行相同的操作,但接受数组中的实际参数
_get.apply(this, [url, config, retries, deferred]);
当您不确定要传递给函数的参数数量时,此选项非常有用。创建一个函数副本,并将此
设置为第一个参数
var f = _get.bind(this);
f(url, config, retries, deferred);
您想要使用的是基本上是bind
,但是该函数会立即被调用。第一个参数是this
的值,而下面的任何参数都将传递给正在调用的函数
_get.call(this, url, config, retries, deferred);
call
有一个被调用的姐妹函数,该函数执行相同的操作,但接受数组中的实际参数
_get.apply(this, [url, config, retries, deferred]);
当您不确定要传递给函数的参数数量时,此功能非常有用