你能解释一下区别吗?
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"发布于 2017-07-10 16:13:30
( 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('+')) // error3)为什么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之后如何解除方法吗?
不能使用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, 1https://stackoverflow.com/questions/45016404
复制相似问题