0

我似乎无法从函数返回对象,函数内部的 console.log 可以很好地打印出属性值,但是一旦在函数之外我得到“未捕获的 ReferenceError:firstOn 未定义”

任何帮助将不胜感激,谢谢!

myElement = document.getElementById("testButton");

function Server(name,tables,startTime) {
    this.name = name;
    this.tables = tables;
    this.startTime = startTime;
}


document.forms.server1.button.onclick = function() {
    var name = document.forms.server1.servername.value;
    var tables = document.forms.server1.servertables.value;
    var startTime = document.forms.server1.servertime.value;

    var firstOn = new Server(name,tables,startTime);

    document.forms.server1.button.innerHTML = "Saved!";

    console.log(firstOn.name);
    console.log(firstOn.tables);
    console.log(firstOn.startTime);

    return firstOn;

};

myElement.onclick = function() {
    console.log(firstOn.name);
    console.log(firstOn.tables);
    console.log(firstOn.startTime);

};
4

4 回答 4

3

该 firstOn 对象是在本地函数范围内创建的。它不会在第二个函数中全局可用。

于 2012-07-24T21:10:15.047 回答
0

I think this is the appropriate solution to my problem.

myElement = document.getElementById("testButton");

function Server(name,tables,startTime) {
    this.name = name;
    this.tables = tables;
    this.startTime = startTime;
}

var firstOn = new Server();

document.forms.server1.button.onclick = function() {
    firstOn.name = document.forms.server1.servername.value;
    firstOn.tables = document.forms.server1.servertables.value;
    firstOn.startTime = document.forms.server1.servertime.value;

    document.forms.server1.button.innerHTML = "Saved!";

    console.log(firstOn.name);
    console.log(firstOn.tables);
    console.log(firstOn.startTime);

    return firstOn;

};

myElement.onclick = function() {
   console.log(firstOn.name);
   console.log(firstOn.tables);
   console.log(firstOn.startTime);
};
于 2012-07-24T21:14:38.997 回答
0

firstOn is an object that was created and returned from the document.forms.server1.button.onclick event handler. The return value from that event handler went into the system (that's where event handlers return to) and was never stored anywhere so it was cleaned up by the system with garbage collection.

Meanwhile, your myElement.onclick event handler does NOT have access to the firstOn object because it wasn't saved anywhere that myElement.onclick can reach.

If you want firstOn to be usable after the document.forms.server1.button.onclick event handler, you have to save it somewhere that the second click handler can each. That could be in a global variable or it could be a property of some other object that is globally accessible. As your code is written right now, the firstOn object is created, but never stored anywhere so it is happily cleaned up by the garbage collector and is not reachable by other code.

于 2012-07-24T21:15:02.507 回答
0
var firstOn = new winMain.Server(name,tables,startTime);
于 2012-11-08T18:30:33.513 回答