DEV Community

loading...
Cover image for JavaScript Arrow & Regular functions case study

JavaScript Arrow & Regular functions case study

yeahch profile image ch ・1 min read

We know the differences between arrow and regular functions in JavaScript. But sometimes I often meet difficult situations to predict the running results of JavaScript functions correctly.
So I have built simple test scripts to explain deeper about JavaScript functions and introduce here.
For the beginners, please visit here.

const case1 = {
    name: "Case1",
  fnArrow: () => {
    console.log("case1/fnArrow: ", this.name)
  },
  fnRegular: function(){
    console.log("case1/fnRegular: ", this.name)
  },
  fnArrowOutside: () => {
    console.log("case1/fnArrowOutside: ", this.name)
  },
  fnRegularOutside: function(){
    console.log("case1/fnRegularOutside: ", this.name)
  },
}

class Case2 {
    constructor() {
    this.name = "Case2"
  }
  fnArrow = () => {
    console.log("case2/fnArrow: ", this.name)
  }
  fnRegular(){
    console.log("case2/fnRegular: ", this.name)
  }
  fnArrowOutside = () => {
    console.log("case2/fnArrowOutside: ", this.name)
  }
  fnRegularOutside(){
    console.log("case2/fnRegularOutside: ", this.name)
  }
}
const case2 = new Case2()

case1.fnArrow();
case1.fnRegular();
case2.fnArrow();
case2.fnRegular();

setTimeout(case1.fnArrowOutside, 100);
setTimeout(case1.fnRegularOutside, 200);
setTimeout(case2.fnArrowOutside, 300);
setTimeout(case2.fnRegularOutside, 400);
Enter fullscreen mode Exit fullscreen mode

And this is a running result.
Alt Text

Discussion

pic
Editor guide