Javascript 使用bind保存函数';在「;这";范围
我正在玩bind,下面是我的作品:Javascript 使用bind保存函数';在「;这";范围,javascript,bind,Javascript,Bind,我正在玩bind,下面是我的作品: webSQL.InsertTransaction = function(qry,CurrentRow) { var local = {}; // Clone the webSQL.Insert function and add 2 parameters: local.InsertTransaction = webSQL.Insert.bind(this,qry,CurrentRow); // Call webSQL.Insert
webSQL.InsertTransaction = function(qry,CurrentRow) {
var local = {};
// Clone the webSQL.Insert function and add 2 parameters:
local.InsertTransaction = webSQL.Insert.bind(this,qry,CurrentRow);
// Call webSQL.Insert(qry,CurrentRow,Transaction)
dbo.transaction(local.InsertTransaction);
}
webSQL.Insert = function(qry,CurrentRow,Transaction) {}
我想把它简化得更简单一些。我是否可以不必指定arguments范围内的2个变量,而是执行以下操作:
local.InsertTransaction = webSQL.Insert.bind(webSQL.InsertTransaction)
也许吧。我的想法是webSQL.Insert可以从它的“this.arguments”中引用qry和CurrentRow。我不知道为什么要首先使用分配给
本地
变量的对象
你所做的就是给它一个函数,然后把这个函数取出来。为什么不跳过这一步呢
webSQL.InsertTransaction = function(qry,CurrentRow) {
dbo.transaction(webSQL.Insert.bind(this,qry,CurrentRow));
}
您是否尝试过
webSQL.Insert.bind(this,arguments)
?好吧,这是可行的,但是我必须引用arg[0].xxx[arg[1]],它不是非常自我记录的……我想使用this作用域。@Phillip:this
与作用域无关。如果您想要this.qry
,您需要手动将qry
分配给this
,就像this.qry=qry
。这是因为我试图理解绑定就是一切。@Phillip:总体来说很简单。.bind()
有效地返回调用它的函数的副本。。。在您的例子中,webSQL.Insert
函数。传递给.bind()
的第一个参数将永久设置Insert
函数的此
值。.bind()
的其余参数将永久性地将第一个参数设置为插入
副本。在实际调用新的Insert
时传递的任何参数都将位于绑定的参数之后。我如何构造它,以便webSQL.Insert使用this.qry和this.CurrentRow?webSQL.InsertTransaction=函数({dbo.transaction(webSQL.Insert.bind(this));}
然后执行webSQL.InsertTransaction.apply({qry,CurrentRow})
应该执行webSQL.InsertTransaction
传递qry
和CurrentRow
作为对象的一部分作为this
传递,然后您可以将其作为this.qry
使用,或者将this
作为本地this
上下文再次传递给其他函数等等。谢谢Francois!播放后我意识到“this”范围过于脆弱,无法依赖,因此我将坚持目前的编写方式。