0

我是 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();
4

2 回答 2

6

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

var myFieldset = new Fieldset();

myFieldset.getFieldset();
于 2012-06-13T15:54:04.667 回答
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();

}
于 2012-06-13T15:54:14.870 回答