Reputation: 316
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.
Upvotes: 1
Views: 3449
Reputation: 298
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/
Upvotes: 2
Reputation: 29634
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;
};
Upvotes: 1