1

У меня есть функция:

function CrFunc(){
  // this1
  return function(){
    //this2
    this.x++;
  }
}

Она вызывается так :

var Nfunc = CrFunc.call(SomeObj); 
Nfunc();

Как сделать this2 = this1? Т.е. Чтобы возвращалась функция с this'ом объекта. Кроме как

Nfunc.call(SomeObj);//apply

это нельзя больше никак реализовать?

Frog
  • 491

2 Answers2

1
function CrFunc(){
  // this1
  return (function(){
    //this2
    this.x++;
  }).bind(this); // this is this1
}
1

Можно также использовать стрелочные функции.

function CrFunc() {
  this.x = 0;
  return () => this.x++;
}

const d = CrFunc();

console.log(d()); console.log(d());

ymd
  • 1,626