有人可以解释以下代码片段中的 function(tx)
,来自此页面:http://www.webkit.org/demos/sticky-notes/ .
tx
分配在哪里以及如何分配?我看过here以获取信息,但我仍然一无所知。
我想我的理解是,对象的 saveAsNew 方法被定义为匿名函数,它首先创建时间戳并创建对自身的本地引用 (note=this),并且然后调用 db 对象的 transaction 方法,为该方法提供一个参数,该参数是另一个具有参数 tx 的匿名函数。但我不明白 tx 是从哪里来的。
.
.
.
saveAsNew: function()
{
this.timestamp = new Date().getTime();
var note = this;
db.transaction(function (tx)
{
tx.executeSql("INSERT INTO WebKitStickyNotes (id, note, timestamp, left, top, zindex) VALUES (?, ?, ?, ?, ?, ?)", [note.id, note.text, note.timestamp, note.left, note.top, note.zIndex]);
});
},
.
.
.
最佳答案
首先,tx
是一个参数定义。您可以选择任何名称,也可以是bar
。它与将函数定义为
function foo(bar) {
}
如果您想知道“谁”传递了这个参数,那么它可能是 db.transaction
。您将函数作为 callback [Wikipedia] 传递.某处 db.transaction
将调用:
callback(transaction);
也许这个例子有助于它理解:
function hello(callback) {
// do some very important world changing computations... then:
callback('Hello ');
}
hello(function(foobar) {
alert(foobar + 'Tim!');
});
// alerts 'Hello Tim!'
此处,hello
函数将一个参数传递给回调函数。
关于javascript参数匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7191222/