3

我想让函数 B 工作,而无需将指令代码设置为函数 A。在实用术语中,在矩形顶部显示文本。

在这个问题中,按钮 A 用于创建“纸”和一个矩形(使用 Raphael 库)。按钮 B 用于在矩形顶部添加文本。HTML 代码如下所示:

<button onClick="func.A()">Func A</button>
<button onClick="func.B()">Func B</button>

JavaScript 代码如下所示:

var func = (function functie($) {
    return { 
        A: function() {
            // Creates canvas 320 × 200 at 10, 50
            var paper = Raphael(10, 50, 320, 200);
            // Creates rectangle
            var bg = paper.rect(0, 0, 320, 200);
            // Sets the fill attribute of the circle to red (#f00)
            bg.attr("fill", "#f00");
            // Sets the stroke attribute of the circle to white
            bg.attr("stroke", "#fff");
        },
        B: function() {
            var t = paper.text(40, 15, "");
            t.attr('text',"new text here");
            t.attr();
        };
 })();

问题是当函数 B 的指令代码(var t = paper.text(40, 15, ""); 等等)放在函数 B 中时,我尝试添加的文本不会被添加到矩形。

如果函数 B 的指令代码放在函数 A 中,那么它会起作用,但这不是我想要的。我想让功能 B 工作而无需将指令代码设置为功能 A。

我希望这个问题足够清楚,可以理解。

4

1 回答 1

2

当您在函数 A 中声明“var paper”时,该变量是函数 A 的本地变量。如果要在函数调用之间共享状态信息,则必须将状态信息存储在对象的属性中,而不是本地变量中:

var func = (function functie($) {
return { 
    paper: null,
    A: function() {
        // Creates canvas 320 × 200 at 10, 50
        this.paper = Raphael(10, 50, 320, 200);
        // Creates rectangle
        var bg = paper.rect(0, 0, 320, 200);
        // Sets the fill attribute of the circle to red (#f00)
        bg.attr("fill", "#f00");
        // Sets the stroke attribute of the circle to white
        bg.attr("stroke", "#fff");
    },
    B: function() {
        var t = this.paper.text(40, 15, "");
        t.attr('text',"new text here");
        t.attr();
    };
})();
于 2013-03-13T16:33:23.960 回答