0

Trying to get my head around javascript OOP, why is this causing the test method to print the entire function definition as if it was a string?

var Myclass = function Myclass(){
    this.connection = make_ajax();
    this.hasConnection = function(){return this.connection};

    this.test = function(){
        console.log(this.hasConnection); 
    }
}
var x = new Myclass();
x.test();

Result:

log: function(){return this.connection}

5
  • apologies I made a change Commented Feb 20, 2014 at 14:07
  • 1
    Because you're not calling it Commented Feb 20, 2014 at 14:07
  • Also, what's the code of make_ajax? Commented Feb 20, 2014 at 14:07
  • var Myclass = function Myclass() should either by var Myclass = function() or function Myclass() Commented Feb 20, 2014 at 14:08
  • There's also a missing } in the end. Commented Feb 20, 2014 at 14:09

2 Answers 2

3

Because... you're not calling the function. You're logging the function itself, and since logging requires a string it calls the built-in toString method which returns the function as a string.

Try console.log(this.hasConnection());

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

3 Comments

Thanks for the insight, say I wanted hasConnection to remain a property with out having to call it, is there another way to store the result of the function inside the variable?
Isn't that just this.connection?
I suppose it could be yeah I just wanted an official bool, I like to make things more complicated for my self :P, i shall now remove the pointless addition but thanks for clearing up the function call thing :)
0

When you

consloe.log(this.hasConnection);

you are logging the actual function, not the result of calling the function. Try changing this line to

consloe.log(this.hasConnection());

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.