-2

The following code outputs dafunc: this.foo = bar

var myObject = {
    foo: "bar",
    dafunc: function() {
        console.log("dafunc:  this.foo = " + this.foo);
    }
};
myObject.dafunc();

Why?

Why doesn't the function dafunc have its own scope where this.foo is undefined? Don't functions have their own this in Javascript?

CodyBugstein
  • 17,496
  • 50
  • 159
  • 312
  • See: https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch1.md#its-scope – timolawl May 03 '16 at 02:34
  • In virtually all OOP languages, `this` (or equivalent) refers to the object the function is a member of. It sounds like you expect `this` to behave like a *variable scope*; for that there's already the, well, *variable scope*, `this` doesn't have to duplicate that functionality. – deceze May 03 '16 at 02:44

3 Answers3

1

Functions don't have their own this, it is decided by the caller.

If you do myObject.daFunc() that will be myObject.

If you do var x = myObject.daFunc; x(); it will not be something useful.

If you do myObject.daFunc.apply(somethingElse) it will be somethingElse.


I think where the confusion comes from is that the this inside of the function is unrelated to the this in the scope that defined the function. So in that way, the function does have its own this.

var myObject = {
  foo: "bar",
  dafunc: function() {
      setTimeout(function(){
        // now we lost "this", this doesn't work
        console.log("dafunc:  this.foo = " + this.foo);
      }, 0);
  } 
};

This is where the "fat-array" syntax that some versions of Javascript have comes in. Here this carries over from the defining scope:

      setTimeout( () => {
        // fat array "preserves" this
        console.log("dafunc:  this.foo = " + this.foo);
      }, 0);
Thilo
  • 241,635
  • 91
  • 474
  • 626
0

When you call it like this: myObject.dafunc(); the this value is myObject

in your code, if you try foo what happens? (its undefined)

omarjmh
  • 11,814
  • 6
  • 29
  • 40
0

In javascript, this refers to the object the function is being called from. The scope is considered using the object. Since function is called using the myobject object, it consists of myobject's scope which has foo defined. I think if said just foo instead of this.foo, it would consider the new foo variable, not the one from myobject's scope.

arya stark
  • 63
  • 1
  • 9