0

I have a javascript object with a handful of methods, and some of the methods reference each other. The methods become undefined in some situations, regardless of using the key word "this" with them. I'm not sure how to go about it. Here is a snippet of my object below. Method getContent() when accessed in onClickMngLinksBtn method becomes undefined when a button with onClickMngLinksBtn event binding is clicked. This same method works fine when accessed with:

InLineLinksObj.getContent() 

I'm hoping the solution is something very basic to Objects in javascript. Any help is much appreciated.

function InLineLinks(formController, fieldController) 
{
   ....

    this.getContent = function(){    
        var field = this.getFieldController().getCustomFieldByName(this.content_field); 
        if(field){
            return field.getValue();            
        }
        return null;
    };

    this.onClickMngLinksBtn = function(){  
        var links = [];
        var txt = this.getContent();  
    }   
    ....  
}
lw0
  • 189
  • 2
  • 9
  • What are the contexts these methods are called? What contexts are undefined? And what contexts are they defined? Examples please. – bloodyKnuckles Jun 24 '14 at 21:54
  • The InLineLinks object gets created, and the button gets added after the content is loaded on "document ready". – lw0 Jun 24 '14 at 22:00

2 Answers2

1

See here, here or here, or many other places for an explanation of scope and the this keyword in javascript. Essentially,

this always refers to the “owner” of the function we're executing

and when your method is triggered by a DOM event, then the owner is either the window or the HTML element that was clicked (or moused over, etc.), instead of the containing object.

A simple way around it in your case is to define a second variable self which will retain a reference to the containing object.

function InLineLinks(formController, fieldController) {
    var self = this;
    ....

    self.getContent = function(){    
        var field = self.getFieldController().getCustomFieldByName(self.content_field); 
        if(field){
            return field.getValue();            
        }
        return null;
    };

    self.onClickMngLinksBtn = function(){  
        var links = [];
        var txt = self.getContent();  
    }   
    ....  
}
Community
  • 1
  • 1
Stuart
  • 7,007
  • 1
  • 16
  • 25
0

The way you have it, InLineLinks is a constructor and getContent is a method of it's instances.

Then, you must instantiate InLineLinks to reach getContent:

new InLineLinks().getContent()
Oriol
  • 225,583
  • 46
  • 371
  • 457