具體結論可參見《javascript下動態this與動態綁定執行個體代碼》。本文專註設計一個無侵入的綁定函數。
<script> window.name = "the window object" function scopeTest() { return this.name } // calling the function in global scope: scopeTest() // -> "the window object" var foo = { name: "the foo object!", otherScopeTest: function() { return this.name } } foo.otherScopeTest() // -> "the foo object!" </script>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]
基於不擴充原生對象的原則,弄了這個bind函數(dom為範圍),用法與Prototype架構的bind差不多。
複製代碼 代碼如下:
dom.bind = function(fn,context){
//第二個參數如果你喜歡的話,也可以改為thisObject,scope,
//總之,是一個新的範圍對象
if (arguments.length < 2 && context===undefined) return fn;
var method = fn,
slice = Array.prototype.slice,
args = slice.call(arguments, 2) ;
return function(){//這裡傳入原fn的參數
var array = slice.call(arguments, 0);
method.apply(context,args.concat(array))
}
用法:第一個參數為需要綁定範圍的函數,第二個為window或各種對象,其他參數隨意。
<script> dom = {}; dom.bind = function(fn,context){ if (arguments.length < 2 && context===undefined) return fn; var method = fn, slice = Array.prototype.slice, args = slice.call(arguments, 2); return function(){//這裡傳入原fn的參數 var array = slice.call(arguments, 0); method.apply(context,args.concat(array)) } } window.name = 'This is window'; var jj = { name: '這是jj', alertName: function() {//綁定失效 alert(this.name); } }; var kk = { name:"kkです" } function run(f) { f(); } run(jj.alertName); var fx2 = dom.bind(jj.alertName,jj) run(fx2); var fx3 = dom.bind(jj.alertName,window) run(fx3); var fx4 = dom.bind(jj.alertName,kk) run(fx4); </script>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]
另一個例子:
<script> dom = {}; dom.bind = function(fn,context){ if (arguments.length < 2 && context===undefined) return fn; var method = fn, slice = Array.prototype.slice, args = slice.call(arguments, 2); return function(){//這裡傳入原fn的參數 var array = slice.call(arguments, 0); method.apply(context,args.concat(array)) } } var obj = { name: 'A nice demo', fx: function() { alert(this.name + '\n' + Array.prototype.slice.call(arguments,0).join(', ')); } }; var fx2 = dom.bind(obj.fx,obj, 1, 2, 3); fx2(4, 5); // Alerts the proper name, then "1, 2, 3, 4, 5" </script>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]