如何运行嵌套的javascript函数?

时间:2012-06-13 15:51:41

标签: javascript

我是javascript中面向对象编程的新手,我正在尝试理解我正在处理的项目中的一些函数。

我如何调用/运行内部函数(列出'this.getFieldset = function(){')来执行?

function Fieldset() {

    this.id = "";
    this.content = document.createElement("DIV");
    this.content.id = "content";
    this.title = "Title";

    this.getFieldset = function() {

        var div = document.createElement("DIV");
        div.id = this.id;
        var span = document.createElement("SPAN");
        var fieldset = document.createElement("DIV");
        fieldset.id = "fieldset";
        var header = document.createElement("DIV");
        header.id = "header";
        span.appendChild(document.createTextNode(this.title));
        header.appendChild(span);
        div.appendChild(header);
        div.appendChild(this.content);
        div.appendChild(fieldset);

        return div;
    }
}

var myFieldset = new Fieldset();
myFieldset.getFieldset();

2 个答案:

答案 0 :(得分:6)

首先你应该创建一个Fieldset的实例,然后你就可以调用它的函数(称为方法):

var myFieldset = new Fieldset();

myFieldset.getFieldset();

答案 1 :(得分:0)

    function Fieldset() {

    this.id = "";
    this.content = document.createElement("DIV");
    this.content.id = "content";
    this.title = "Title";

    this.getFieldset = function() {

        var div = document.createElement("DIV");
        div.id = this.id;
        var span = document.createElement("SPAN");
        //var fieldset = document.createElement("DIV");
        //fieldset.id = "fieldset";
        var header = document.createElement("DIV");
        header.id = "header";
        span.appendChild(document.createTextNode(this.title));
        header.appendChild(span);
        div.appendChild(header);
        div.appendChild(this.content);
        div.appendChild(fieldset);

        window.alert("test");

        return div;
    }

    //add call to run function
    this.getFieldset();

}