从 html 调用 javascript 对象方法 [英] call javascript object method from html

查看:61
本文介绍了从 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;
};

这篇关于从 html 调用 javascript 对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆