你能解釋的區別:約束力,借款方法
var obj = {
0: "A",
1: "B",
2: "C",
length: 3,
print: function(){ console.log(this) }
};
//A (borrowing method. No changes in obj):
[].join.call(obj, "+"); //-> "A+B+C"
//B:
obj.join = [].join.bind(obj);
obj.join("+"); //-> "A+B+C"
var oj = obj.join;
oj("-"); //-> "A-B-C" (binded to obj)
//C:
obj.j = [].join;
obj.j("++"); //-> "A+B+C"
var j = obj.j;
j("-"); //-> "A-B-C" (it still binded!)
//D:
var join = [].join.bind(obj)
join("+"); //-> "A+B+C"
//E (not working: [] is a new array every time):
[].join.bind(obj);
[].join("+"); //expected: "A+B+C" but I have: ""
//F (Danger!)
Array.prototype.join = [].join.bind(obj);
[].join("+"); //"A+B+C"
你能否解釋一下是有A和B之間的區別?
B和C有什麼區別?
爲什麼E不起作用?
(額外的問題)你能解釋如何在F後解除綁定方法嗎?
Array.prototype.join = [].join.bind(null);
[].join([1,2,3,4],"+"); //-> "ABC"
[請不要把問題標題標籤(https://stackoverflow.com/help/tagging) – Liam
嘛,E不因爲工作' [] .join.bind(obj)'和'[] .join(「+」)'是兩個完全獨立的數組。 A和B之間的區別在於,你實際上是用'call'調用函數,而在B中你是用綁定的'this'上下文返回函數,並將對象的連接函數設置爲新綁定的函數。 – mhodges
你在問幾個問題。 – canon