Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested function inside literal Object

if in a literal object i try to reference a function using "this" inside a nested property/function, this don't work. Why? A nested property have it's own scope?

For example, i want to call f1 from inside d.f2:

var object = {    

  a: "Var a",
  b: "Var b",
  c: "Var c",

  f1: function() {
    alert("This is f1");
  },

  d: {
      f2: function() {
       this.f1();
    }
  },

  e: {
      f3: function() {
        alert("This is f3");
     }
  }
}

object.f1(); // Work
object.d.f2(); // Don't Work. object.e.f3(); // Work

Thanks, Andrea.

like image 616
Andrea Avatar asked Apr 18 '10 10:04

Andrea


2 Answers

this refers to d inside f2 and not object. You could store a reference to object, or call object directly, or use call/apply to call the function and explicitly tell it what this means inside that function:

object.d.f2.call(object); // now this refers to object inside f2
like image 163
Anurag Avatar answered Sep 21 '22 04:09

Anurag


Here's an alternative approach which doesn't change the context of this inside f2(), based on @slaver113's idea:

var object = (function() {
  var _this = {
    f1: function() {
      alert('This is f1');
    },
    d: {
      f2: function() {
        _this.f1();
      }
    }
  }

  return _this;
})();

object.d.f2(); // Alerts 'This is f1'
like image 31
WynandB Avatar answered Sep 22 '22 04:09

WynandB