1

I'm relatively new to Javascript programming. I'm working on an example and am having difficulty in invoking a method on an object from HTML. I suspect this has something to do with the scoping or externalization of the methods, but I'm not sure.

index.html:

<script type="text/javascript">
var f = new Fred();
f.bar();
f.foo();
</script>

Fred.js:

function Fred() {
this.a = 1;

function foo() {
    if (a == 1) {
        a++;
    } 
    var e = 0;
}

this.bar = function () {
    var a = 3;
    var b = 4;
};

this.c = 3;
this.d = 4;

}

The call to bar() works, the call to foo() does not.

2 Answers 2

2

Yes, you are right, this does have to do with scoping and the concept of closures. You can think of the foo() function as being a "private" method if you are familiar with other object oriented languages like Java or C#. It is only available inside the scope of your Fred() object. The bar() function is "public" in the sense that declaring it with this.bar adds it to the publicly available properties of your Fred() object. So, to also make foo() "public", then declare it as:

this.foo = function () {
    if (a == 1) {
        a++;
    } 
    var e = 0;
}

For a more in depth explanation of closures in javaScript, try this link: http://www.sitepoint.com/javascript-closures-demystified/

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

1 Comment

Thanks, I figured I could do that, but I wanted to understand why. Also explains why I could invoke both from within the object. Thanks for the pointer on closures.
1

your not assigning a function pointer to foo. Change it to

this.foo = function() {
    if (a == 1) {
        a++;
    } 
    var e = 0;
};

like you've done:

this.bar = function () {
    var a = 3;
    var b = 4;
};

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.