1

As we know, JavaScript is a Lexical Scope language:

var a = 1;

function foo() {
  console.log(a);
}

function bar() {
  var a = 2;
  foo(); 
}

bar() // 1

But when it comes to this, javascript show Dynamic Scope feature with this keyword. For example:

var obj = {
  foo: function(){
    console.log(this)
  }
}

var bar = obj.foo
obj.foo() // obj
bar() // window

What is their relationship on earth?

guerbai
  • 325
  • 4
  • 11
  • Have you attempted to google this question? There is plenty of documentation online already that explains how `this` works in JavaScript. – Code-Apprentice Sep 20 '18 at 03:18

2 Answers2

0

Functions in javascript can also be closures around data. As such this represents the context of the closure. You can override it e.g.

var MyObject = {name: 'your name'}

function NamePrinter() {
    console.log(this.name)
}

NamePrinter = NamePrinter.bind(MyObject)
NamePrinter();

Also please note this is a contrived example. I wouldn't typically try to overwrite my context this way. It is useful sometimes, such as when passing functions around and binding them in some other context, you can make something useful for cross cutting utilities

Jordan Brooklyn
  • 225
  • 1
  • 11
0

In Javascript, what matters more than where the function is defined is from where the function is being invoked and with what context.

In your 1st case both foo and bar are being called from window scope(considering it runs in a browser) hence it returns 1.

Whereas, in your second case

var bar = obj.foo
obj.foo() // obj
bar() // window

obj.foo() invokes foo with obj context, hence this refers to obj. but in case of bar; it refers to the function foo and since bar is being called in global scope, this refers to window.

Roy
  • 471
  • 5
  • 15