Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Please, is sample code of "this reference" in Arraw function chapter explicit? #111

Closed
Lucky4 opened this issue Mar 10, 2018 · 0 comments
Closed

Comments

@Lucky4
Copy link

Lucky4 commented Mar 10, 2018

This is the origin sample code, the result is 1.

function myFunc() {
  this.myVar = 0;
  setTimeout(() => {
    this.myVar++;
    console.log(this.myVar);
  }, 0);
}

myFunc(); // 1

And the following code has the same reuslt 1.

function myFunc() {
  this.myVar = 0;
  setTimeout(function() {
    this.myVar++;
    console.log(this.myVar);
  }, 0);
}

myFunc(); // 1

And i think use an object manner write this example maybe better? Like this:

myVar = 123;

var object= {
  myVar: 0,
  f: function () {
    setTimeout(() => {
      this.myVar++;
      console.log(this.myVar);
    }, 0);
  }
}

object.f(); // 1

And this is the comparing code:

myVar = 123;

var object= {
  myVar: 0,
  f: function () {
    setTimeout(function() {
      this.myVar++;
      console.log(this.myVar);
    }, 0);
  }
}

object.f(); // 124
@Lucky4 Lucky4 closed this as completed Mar 11, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant