2016-10-09 101 views
-1

我的印象是,我可以通過使用bind將參數傳遞給一個函數,然後調用這些參數,就好像它們已經正常傳遞一樣。爲什麼我需要這樣做:爲什麼bind看起來像數組一樣呈現參數?

$(document).ready(function() { 
    var func = function(button) { 
    button[0].on('click', function() { 
     alert('Hello World.'); 
    }) 
    } 
    func.bind(null, [$('.button')])(); 
}); 

當好像我應該能夠只是這樣做:

$(document).ready(function() { 
    var func = function(button) { 
    button.on('click', function() { 
     alert('Hello World.'); 
    }) 
    } 
    func.bind(null, [$('.button')])(); 
}); 

例,治療button參數作爲一個數組:

$(document).ready(function() { 
 
    var func = function(button) { 
 
    button[0].on('click', function() { 
 
     alert('Hello World.'); 
 
    }) 
 
    } 
 
    func.bind(null, [$('.button')])(); 
 
});
html, body, div { 
 
    padding:0; 
 
    margin:0; 
 
    display:flex; 
 
    justify-content:center; 
 
} 
 

 
.button { 
 
    background-color:gray; 
 
    margin:50px; 
 
    padding:50px; 
 
    width:50%; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div class="button">Button</div>

+1

它將它視爲一個數組,因爲你綁定了一個數組。 –

回答

3

bind()用於將當前調用範圍綁定到函數,以便即使從其他位置調用該函數,它也會知道該綁定範圍中的局部變量。

您要找的是apply()

var func = function(button) { 
 
    button.on('click', function() { 
 
    console.log('hello world'); 
 
    }); 
 
} 
 

 
func.apply(this, [$('.button')]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class="button">Click Me</button>

爲了完整起見,有也是較爲常用的一個call()功能。它不是參數數組,而是在初始範圍參數後面使用參數列表。

func.call(this, $('.button')); 
+2

'.apply()'更好,但即使這樣也沒有太大意義,因爲可以使用'.call()'來代替。不要忘記刪除尾部的'()' –

+1

啊是的,我錯過了後面的'()'。我最初建議使用'call()',但似乎OP想要傳遞一個參數數組,所以'apply()'是最正確的方法。 – Soviut

+0

我明白了,是的,如果OP已經有一個數組,那麼'.apply()'是解決方案。 –

2

您正在使用.bind錯誤。你不應該給它的參數數組,你應該給自己的論點:

function print(x, y, z) { 
 
    console.log(x, y, z);  
 
} 
 

 
print12 = print.bind(null, 1, 2); 
 

 
print12(3); // 1, 2, 3

而且,Soviut提到的,如果你調用.bind(...)(),你可能想.apply()或改爲.call()

+0

哦,如果我有一個動態數量的參數我想傳遞給函數呢?編輯:我看到,上面的答案顯示我需要使用的是'apply' – curiosity5678

+0

@ curiosity5678使用類似['.apply(null,[arg1,arg2,arg3,...])'](https:/ /developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/apply) – Frxstrem

+0

@ curiosity5678如果你想用動態數量的參數調用'bind',你可以使用'Function.bind.apply(myFunction ,[thisValue,arg1,arg2/* ... * /])' – Oriol

相關問題