2

Main concern is efficiency.

I am working on javascript scopes and one thing that I am confused about is this inside a function.

I have read many answers and I understand them. But what I am concerned about is efficiency. Have a look at my code.

  class Fancy {
    constructor () {
  }

  checkScope (callback) {
    console.log('Inside checkScope');
    callback ();
  }
}

class Prog {
  constructor () {
    this.name = 'myProg';
    this.fancy = new Fancy ();
  }

  run () {
    var that = this;
    this.fancy.checkScope(function () {
      console.log('Name ', that.name);
    });
  }
}

var prog = new Prog ();
prog.run();

Now in run() I am storing reference of this in a local variable that. This is working for me. But is it safe? Is it efficient? If no, please suggest me a good strategy/trick.

Thanks :)

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
Junejo
  • 717
  • 1
  • 7
  • 14

1 Answers1

2

Yes it is safe, but you can use the new arrow syntax.It preserve the this.

 class Fancy {
    constructor () {
  }

  checkScope (callback) {
    console.log('Inside checkScope');
    callback ();
  }
}

class Prog {
  constructor () {
    this.name = 'myProg';
    this.fancy = new Fancy ();
  }

  run () {
    // Here your don't need var that = this, 
    // because the arrow function gets the same this
    this.fancy.checkScope( () => {
      console.log('Name ', this.name);
    });
  }
}

var prog = new Prog ();
prog.run();

Every simple function has it's this, in your case your

 function () {
      console.log('Name ', this.name); // this is undefined in 'strict mode'
    }

has its own this.So you need to keep the this outside the function and use with alias in the function.In ES6 there is a new arrow syntax function.Arrow functions don't override the this. In your case

run () {

        this.fancy.checkScope( () => {
          console.log('Name ', this.name);
        });
      }

the this in the run function and in the parameter function are the same. It means that in the arrow function scope the this refers to that this in which the arrow function was defined.

In the case of efficient, you don't need an extra variable.You don't pollute the local scope with an extra variable. In the performance there is no affect.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • Can you please explain how it going to help? And how it is difference. – Junejo Sep 01 '16 at 07:43
  • @ZulfiqarJunejo see the updated version – Suren Srapyan Sep 01 '16 at 07:48
  • @SurenSrapyan: That's fine, but I think the OP is interested about the "is it efficient?" part. So the question is whether this is more or less efficient than using the regular function scope by casting the "this" to another variable. -- +1 after edit ;D – briosheje Sep 01 '16 at 07:49
  • I like @SurenSrapyan's answer. Thanks. I am accepting the answer. – Junejo Sep 01 '16 at 07:54