[英]javascript arguments anonymous function
有人可以在下面的代码片段中解释function(tx)
: http : //www.webkit.org/demos/sticky-notes/ 。 tx
在何处以及如何分配? 我在这里寻找信息,但仍然在黑暗中。
我认为我理解的是,对象的saveAsNew方法被定义为一个匿名函数,它首先创建一个时间戳并创建一个对它自己的本地引用(note = this),然后调用db对象的事务方法,向该方法提供一个参数,该参数是另一个具有参数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
。 您正在将该函数作为回调传递 [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
函数将一个参数传递给回调函数。
如果我知道什么是transaction()
,我可以帮助你更多。
但我相信它是功能返回的东西。
像click一样有一个返回的event
因此,在transaction
代码中的某个位置,一个变量被发送到该函数,然后您可以在代码中命名和使用该函数。
从早期的代码:
db = openDatabase("NoteTest", "1.0", "HTML5 Database API example", 200000);
您必须查看具有transaction
功能的openDatabase
执行的操作。
函数saveAsNew返回一个以tx为参数的函数:
var new = saveAsNew();
new(tx);
至于tx来自哪里,不可能从这个片段说出来。
db.transaction()函数必须接受一个参数,该参数是一个带有一个参数的函数(在您的示例中为function(tx))。
它可能记录为db.transaction(回调)。
db.transaction()函数将参数tx发送到回调函数(在您的情况下为匿名函数(tx))。
您可以使用任何变量,只要在您的匿名方法定义中使用相同的变量即可。 在调用匿名方法时,事务方法将传递一个值作为第一个参数,并将其分配给tx。
您的代码等同于:
saveAsNew: function()
{
this.timestamp = new Date().getTime();
var note = this;
function booga(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]);
}
db.transaction(booga);
},
“tx”来自“booga(tx)”在哪里? 答:调用booga的人都会传递一个参数,而tx是我们给该参数的名称。
函数调用db.transaction()
本身需要一个参数。 该参数本身是db.transaction()
将调用的函数,当它调用该函数时,它将向它传递一个参数。 名称tx
可以是任何东西,它只是该函数的第一个参数的名称。
你的代码可能是用你传递给db.transaction()
作为匿名函数的函数编写的,就像你在这里做的那样:
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]);
});
或者它可以用这种方式写出来,它会更明显地发生什么,但不是那么紧凑:
function writeSql(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]);
}
db.transaction(writeSql);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.