-1

Could somebody here please get this straight for all of us once and for all?

var parent = {child: function(){
        console.log(this); 
        var log = function(){ 
        console.log(this);}; 
        log();
    }
}

When I call parent.child() I get:

Object{}
Window{}

Other people/ documentation on Mozilla say that this function has been invoked without any context. And

this

will be the object on which the function is invoked. What I don't understand is how on earth this function within another object is considered to be without a context(so this defaulted to the global object). What's the logic here? Thanks

BlackLog
  • 301
  • 1
  • 5
  • 17
  • `log` is called without context. If you want to call it with context, you should do `log.call(this)`. Without context you get `window` in sloppy mode, `undefined` in strict mode. – trincot Nov 15 '16 at 20:49
  • http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – epascarello Nov 15 '16 at 20:51
  • Thanks. I know that. What I wondering is how it is called without a context. – BlackLog Nov 15 '16 at 20:51
  • Because there is no object/property relation involved, like `object.log()`, but just `log()`. – trincot Nov 15 '16 at 20:52

1 Answers1

0

Function referenced at objects are like methods. When you directly call a function by indexing an object, this same object will be referenced by this in the scope the function will generate.

When calling a function without indexing an object, or without setting this context (with apply, bind, call, ...), if it's not at strict mode (or is at least in a global scope when at strict mode) this should be the global object.

When objects are instances of classes/interfaces/functions, their methods also capture this same object for this.

This is how it works for me:

(function() {
    'use strict'
    console.log(this) // undefined
})()

console.log(this) // Window{}