从 html 调用 javascript 对象方法
问题描述:
我对 Javascript 编程比较陌生.我正在编写一个示例,但在从 HTML 调用对象上的方法时遇到困难.我怀疑这与方法的范围或外化有关,但我不确定.
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:
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;
}
对 bar()
的调用有效,对 foo()
的调用无效.
The call to bar()
works, the call to foo()
does not.
答
您没有分配 函数指针指向 foo.改成
your not assigning a function pointer to foo. Change it to
this.foo = function() {
if (a == 1) {
a++;
}
var e = 0;
};
就像你所做的那样:
this.bar = function () {
var a = 3;
var b = 4;
};