Skip to content

Latest commit

 

History

History
48 lines (32 loc) · 1.03 KB

File metadata and controls

48 lines (32 loc) · 1.03 KB

What is this ?

Question time:

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

var stolenFunction = obj.print
obj.print() // this -> object { print: [Function: print] }
stolenFunction() // this -> `window`

Please explain why the values of the last two lines of the function are different ?

Every function is equal tofunc.call(environment, p1, p2)

Actually , func.call(environment, p1, p2) is normal way to call function but func() or object.child.func()

so:

  • obj.print() is equal to obj.print.call(obj)
  • print() is equal to print.call(window)

Example:

obj.print.call(window) // window
obj.print.call(obj) // obj

If the context you pass is null or undefined, then the window object is the default context (the default context in strict mode is undefined)

obj.print.call()  // window, not obj

What is this?

func.call(environment, p1, p2)

this = environment

Reference