0

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/

1
  • Actually hello in your example is not a method, it is a local function defined inside other function Commented Aug 5, 2014 at 9:31

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

7 Comments

I see, thanks! But one additional. How do I call "hello" inside from T now?
@audio_developer: In the second example, you can use this.hello(), within T. You can't when using the first example.
thanks again. I tried exactly that before I asked, but did a typo for the call "this.hello(}" ... I guess this means I need a short break. :-) have a good day!
I discovered another question: Is this a good style to call hello from an inner function with that? jsfiddle.net/9H4JM
@audio_developer: Yea, that works too. That way, you can create private functions.
|
1

function hello is in local scope of T.

define T like this.

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

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.