1

In object literal we should be able to access the methods using this.name, but in my case below I'm using this.init() to trigger a method but gave me undefined function instead. However if I refer to allTabAnimation.init() it works, why is that ?

var allTabAnimation = {
    desktopClick: function (){
        $('.allForms .investorOptions .investorOptions-wrapper .select-options input+label').click(function (e){
            $this = $(this),
            $thisHookNumber  = $(this).data("hook"),
            $allTab = $(".tab-content"),
            $selectedTab  = $(".tab-content[data-hook="+$thisHookNumber+"]"),
            this.init(); // doesn't work
            // allTabAnimation.init(); // this work
        });
    },

init: function (){
    this.condition($selectedTab, $allTab);
},
3bdalla
  • 407
  • 1
  • 10
  • 28
Vincent1989
  • 1,593
  • 2
  • 13
  • 25
  • possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – jdphenix Apr 28 '15 at 06:14
  • Felix Kling's answer on the duplicate is spot on for what you can do. – jdphenix Apr 28 '15 at 06:14

2 Answers2

4

Store this in variable (or use .bind, or $.proxy), because in your case this refers to element not for parent object, like so

var allTabAnimation = {

    desktopClick: function() {
        var self = this;

        $('.allForms .investorOptions .investorOptions-wrapper .select-options input+label').click(function(e) {

            $this = $(this),
                $thisHookNumber = $(this).data("hook"),
                $allTab = $(".tab-content"),
                $selectedTab = $(".tab-content[data-hook=" + $thisHookNumber + "]")

            self.init();
        });
    },

    init: function() {
        this.condition($selectedTab, $allTab);

    }
} 
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
1

The scope (this) changes in the callback, thats why you need to declare it to a variable instead. Following conventions, you should use

var that = this;
keno
  • 83
  • 1
  • 11