一、引
是该学习下了!!!
二、call()
直接看例子
function test(c){
console.log(this.a + this.b + c);
}
var obj = {
a:1,
b:2
}
test.call(obj,3); // 6
大家都说这是 call()
是改变 this
的指向,那到底是什么意思呢?
var obj = {
a:1,
b:2,
test:function(c){
console.log(this.a + this.b + c)
}
}
obj.test(3)
一言不合就上代码,这里的 this
是指向了 call()
的第一个参数对象。
动手实现一下:(应该是最简单的实现了吧)
Function.prototype.myCall = new function(context){
var context = context || windows; // context 即 obj 对象
// var context = context || gobal nodejs中的全局对象与浏览器中不同
//根据上面的思想,就是要把方法绑定到这个 obj 上 ,而此时的 this 仍然为方法本身
context.fn = this;
// 在 obj 内添加此方法
let result = context.fn(...[...arguments].slice(1));
//argements 就是 myCall() 的参数,然后在 obj 内执行方法,得到结果
delete context.fn;
return result;
}
三、apply()
和上面的 call()
是差不多的,只是穿参的形式不同,上面是直接传,这里需要把参数转为数组,其他不变。
test.apply(obj,[3]); // 6
好像差距不大,那么实现起来应该也不难,试一下:
Function.prototype.myallpy = new function(context){
var context = context || windows;
if(arguments[1]) {
// 因为 apply() 的第二个参数是个数组,所以直接取数组里的参数展开就行了
let result = context.fn(...arguments);
}else {
let result = context.fn();
}
delete context.fn;
return result
大概的代码和 call()
就差不多了,没多要解释的
四、bind()
var foo = test.bind(obj,3)
foo() //6
// 同上不同的就是,上面的俩个方法是直接调用,而 bind() 是返回一个新函数
不多废话,写…
Function.prototype.mybind() = function(context){
if (typeof this !== 'function'){
throw new TypeError('Error')
}
let self = this
let args = [...arguments].slice(1)
return function(){
self.apply(exector, args)
}
}
写一下,我也更明白了!!!