Dynamic Scope vs Lexical Scope

Everything in JavaScript is actually lexically scoped where you write it to determine what we have available except for this keyword.

const obj = {
  name: "Jay",
  sing: function() {
    console.log("a " + this.name);
    console.log("a " + this )
    var anotherFunc = function () {
      console.log("b", this.name);
      console.log("b", this);
    };
    anotherFunc();
  },
};

obj.sing();
a Jay
a {name:"Jay", sing:f{...}}
b undefined
b Object [global]
  • why b is undefined and get global object? because this keyword is not lexically scoped. It is dynamic scope that it matters how the function was called.

So, we need lexically scoped for this keyword.

1. with ES6

const obj = {
  name: "Jay",
  sing: function() {
    console.log("a " + this.name);
    console.log("a " + this )
    var anotherFunc =  () =>  {
      console.log("b", this.name);
      console.log("b", this);
    };
    anotherFunc();
  },
};

obj.sing();
a Jay
a { name: 'Jay', sing: [Function: sing] }
b Jay
b { name: 'Jay', sing: [Function: sing] }

2. with bind

const obj = {
  name: "Jay",
  sing: function () {
    console.log("a " + this.name);
    console.log("a " + this);
    var anotherFunc = function () {
      console.log("b", this.name);
      console.log("b", this);
    };
    return anotherFunc.bind(this);
  },
};

obj.sing()();
a Jay
a { name: 'Jay', sing: [Function: sing] }
b Jay
b { name: 'Jay', sing: [Function: sing] }

3. with self

const obj = {
  name: "Jay",
  sing: function () {
    console.log("a " + this.name);
    console.log("a " + this);
    var self = this;
    var anotherFunc = function () {
      console.log("b", self.name);
      console.log("b", self);
    };
    anotherFunc();
  },
};

obj.sing();
a Jay
a { name: 'Jay', sing: [Function: sing] }
b Jay
b { name: 'Jay', sing: [Function: sing] }

Leave a Reply

Your email address will not be published.

ANOTE.DEV