audio_developer
audio_developer

Reputation: 105

calling a method from another function in JS (TypeError exception)

I guess it's really a newbie error, but I can't get it running. I have an "calculator" object t, which contains a lot of function to calculate values. I need to use these functions from my "calculator" object to get some values in another function. I striped it down to the following, but I get an TypeError exceptio when I call the t.hello() method. Any ideas?

 var t = new T();
 two();

 function T() {
     function hello() {
         alert("hello");
     }
 }

 function two() {

     t.hello();

 }

http://jsfiddle.net/4Cc4F/

Upvotes: 0

Views: 43

Answers (3)

Mayur Borad
Mayur Borad

Reputation: 1295

Try this,

var t = new T();
two();
function T() {
     this.hello = function () {
         alert("hello");
     }
 }    
 function two() {    
     t.hello();    
 } 

see this : http://jsfiddle.net/4Cc4F/2/

Upvotes: 0

Mritunjay
Mritunjay

Reputation: 25882

function hello is in local scope of T.

define T like this.

function T() {
     this.hello = function() {
         alert("hello");
     }
 }

Upvotes: 1

Cerbrus
Cerbrus

Reputation: 72857

You'll need to return an object that contains the function:

function T() {
    return {
        'hello': function () {
            alert("hello");
        }
    }
}

Or specifically define it as an function in T's scope:

function T() {
    this.hello = function() {
        alert("hello");
    }
}

Fiddle

Upvotes: 3

Related Questions