提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
call、apply、bind的区别
call和appply的功能相同,区别在于传参方式的不同,call和apply调用函数时都有一个指定的this,call方法是分别提供参数列表,而apply则是用数组或者类数组来提供参数。
bind和call/apply有一个很重要的区别,当一个函数被call/apply调用时,会被调用;而bind会创建一个新的函数,当这个新的函数别被调用时,bind会将自己的第一个参数作为新函数运行时的this,之后的一序列参数将会在传递的实参前传入作为它的参数。
Tips:11、61
call、apply、bind手写
实现call方法
Function.prototype.call2 = function (context) {
//没传参数或者为 null 是默认是 window
var context = context || (typeof window !== 'undefined' ? window : global)
// 首先要获取调用 call 的函数,用 this 可以获取
context.fn = this
var args = []
for (var i = 1; i < arguments.length; i++) {
args.push('arguments[' + i + ']')
}
eval('context.fn(' + args + ')')
delete context.fn
}
// 测试
var value = 3
var foo = {
value: 2
}
function bar(name, age) {
console.log(this.value)
console.log(name)
console.log(age)
}
bar.call2(null)
// 浏览器环境: 3 undefinde undefinde
// Node环境:undefinde undefinde undefinde
bar.call2(foo, 'cc', 18) // 2 cc 18
实现apply方法
Function.prototype.apply2 = function (context, arr) {
var context = context || (typeof window !== 'undefined' ? window : global)
context.fn = this;
var result;
if (!arr) {
result = context.fn();
}
else {
var args = [];
for (var i = 0, len = arr.length; i < len; i++) {
args.push('arr[' + i + ']');
}
result = eval('context.fn(' + args + ')')
}
delete context.fn
return result;
}
// 测试:
var value = 3
var foo = {
value: 2
}
function bar(name, age) {
console.log(this.value)
console.log(name)
console.log(age)
}
bar.apply2(null)
// 浏览器环境: 3 undefinde undefinde
// Node环境:undefinde undefinde undefinde
bar.apply2(foo, ['cc', 18]) // 2 cc 18
实现bind方法
Function.prototype.bind2 = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () { },
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}
// 测试
var test = {
name: "jack"
}
var demo = {
name: "rose",
getName: function () { return this.name; }
}
console.log(demo.getName()); // 输出 rose 这里的 this 指向 demo
// 运用 bind 方法更改 this 指向
var another2 = demo.getName.bind2(test);
console.log(another2()); // 输出 jack 这里 this 指向了 test 对象了
Tips:不会,需加强