Javascript 装订、借用方法
你能解释一下区别吗:Javascript 装订、借用方法,javascript,arrays,bind,Javascript,Arrays,Bind,你能解释一下区别吗: 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("+"); //-
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"
1) a和B之间有区别吗
是的,A不修改注释中提到的obj
2) B和C之间有区别吗
除了打印“A++B++C”之外,是的。B是显式绑定的,而C不是,这意味着它可能会丢失上下文。请尝试以下操作:
var fn = obj.join
var fn2 = obj.j
console.log(fn('+')) // works
console.log(fn2('+')) // error
3) 为什么E不工作
[].join.bind(obj);
// ^ this is an array instance
// calling `join.bind(obj)` makes no modification to that array instance or any other
[].join("+"); //expected: "A+B+C" but I have: ""
// ^ this is different array instance, unaffected by the above call
4) 你能解释一下F之后如何解开方法吗
Array.prototype.join = [].join.bind(null);
[].join([1,2,3,4],"+"); //-> "ABC"
无法解除绑定使用javascript的本机bind
方法绑定的绑定函数。您可以编写自己的不可绑定版本,但这不是本机API的一部分
下面是一个简单的实现:
function bind(fn, context) {
var newFn = function () { return fn.call(context, arguments) }
newFn.unbind = function () { return fn }
return newFn
}
function checkCtx (a) { console.log(this, a) }
checkCtx(1); // Window, 1
bind(checkCtx, {})(1) // {}, 1
bind(checkCtx, {}).unbind()(1) // Window, 1
嗯,E不起作用,因为
[].join.bind(obj)
和[].join(“+”)
是两个完全独立的数组。A和B之间的区别在于,在A中,您实际上是通过call
调用函数,在B中,您是通过绑定此
上下文返回函数,并将对象的连接函数设置为新绑定的函数。您问了几个问题。是的。正确:[].join.bind(obj)和[].join(“+”)是两个完全独立的数组。谢谢你的评论。B和C之间有什么区别?感谢您对如何解除绑定方法的解释和解决方案:**您无法解除绑定**使用javascript本机绑定方法绑定的绑定函数。