请帮忙解析以下代码的的具体用意(问题已添加在代码行中)。
代码背景:这是自定义的this“软绑定”对象的函数(教学用途),为了解决硬绑定所造成函数的灵活性减少的问题(使用硬绑定之后就会无法使用隐式绑定或显示绑定来修改this)。
如能帮忙解释清楚,不胜感激。
if (!Function.prototype.softBind) {
//!Function.prototype.softBind 是不是调用匿名函数的意思?
Function.prototype.softBind = function (obj) {
var fn = this;
var curried = [].slice.call(arguments, 1); //这里为何是1?
var bound = function () {
return fn.apply(
!this || this === (window || global) ? obj : this, //!this 是什么意思?
curried.concat.apply(curried, arguments) // 为何要合并?
);
};
bound.prototype = Object.create(fn.prototype); //这行代码的用意?
return bound;
};
}
//test softBind()
function foo() {
console.log("name:" + this.name);
}
var obj = { name: "obj" },
obj2 = { name: "obj2" },
obj3 = { name: "obj3" };
var fooOBJ = foo.softBind(obj);
fooOBJ(); // Output: name:obj
obj2.foo = obj.foo(obj);
obj2.foo(); // Output: name:obj2
fooOBJ.call(obj3); // Output: name:obj3
setTimeout(obj2.foo, 10); // Output: name:obj
我想你可以从这里找到答案!https://www.cnblogs.com/jokes/p/12417105.html%EF%BC%8C%E5%A6%82
第一行:简单来说,bind函数用于将当前函数和指定对象绑定,返回一个新的函数,当新函数被调用时,代码会在指定对象的上下文中执行。不懂看看这个文章https://blog.csdn.net/liuhe688/article/details/51016768 ,第8行 !this就是取这个函数反过来的意思,如果this结果是true,在!this就是false !this||this 这个返回一定是true