0

I've created a class in Javscript using the prototype Class.Create complete with the initialize function and a few other functions. However, in one of my functions I want to reference another function in the same class, but cannot seem to get the syntax correct.

e.g.

    var sampleClass = Class.create({

            initialize: function(){

                //do the init work here

        },

        functionA: function(){

            //do some more stuff here
        }
        functionB: function(){
            //Do some stuff
            functionA()
        }
}

I've tried calling functionA() , this.functionA() but nothing works I just get errors. I know how to call the functions externally when the class has been instantiated, but not reference a function from within the class itself.

Thanks

2 Answers 2

3

this.functionA()

would be the correct way to call the object's method from within another method of the same object.

but nothing works I just get errors

What errors? If you are getting ‘property functionA not found’, then the probability is that this is pointing in the wrong place. Use Firebug or some alert​s to check what it is. A common problem is that you've detached the method's function from the owner object and passed it to something else:

element.onclick= this.functionB;

when functionB is called back in this case, this will be unset and so will default (very unhelpfully, for debugging) to window. This happens because object.methodname in JavaScript, unlike many other modern scripting languages, only gives you an unbound function object and not a bound method.

The simple way to preserve this, introduced by Prototype and now a standardised part of JavaScript (coming soon to a browser script engine near you), is function.bind:

element.onclick= this.functionB.bind(this);
Sign up to request clarification or add additional context in comments.

Comments

1

Agreed with bobince, except you'll want to use the Event.observe() syntax for attaching event handlers rather than assigning to the element's onclick property. Example:

element.observe('click', this.functionB.bind(this));

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.