做用:javascript
call() 方法就是在使用一个指定 this 值和若干个指定的参数值的前提下调用某个函数或者方法。
var foo = { value : 1 } function bar() { console.log(this.value) } // 若是不对this进行绑定执行bar() 会返回undefined bar.call(foo) // 1
也就是说call()
改变了 this
的指向到了 foo
。java
试想当调用 call 的时候,也就是相似于数组
var foo = { value: 1, bar: function() { console.log(this.value) } } foo.bar() // 1
这样就把 this 指向到了 foo 上,可是这样给 foo 对象加了一个属性,有些瑕疵,不过没关系,执行完删除这个属性就能够完美实现了。app
也就是说步骤能够是这样:函数
下面就试着去实现一下:this
Function.prototype.call2 = function(context) { context.fn = this // this 也就是调用call的函数 var result = context.fn() delete context.fn() return result } var foo = { value: 1 } function bar() { console.log(this.value) } bar.call2(foo) // 1
可是这样有一个小缺陷就是call()
不只能指定this到函数,还能传入给定参数执行函数好比:prototype
var foo = { value: 1 } function bar(name, age) { console.log(name) console.log(age) console.log(this.value) } bar.call(foo, 'black', '18') // black // 18 // 1
特别要注意的一点是,传入的参数的数量是不肯定的,因此咱们要使用arguments
对象,取出除去第一个以外的参数,放到一个数组里:code
Function.prototype.call2 = function(context) { context.fn = this // this 也就是调用call的函数 var args = [...arguments].slice(1) var result = context.fn(...args) delete context.fn() return result } var foo = { value: 1 } function bar(name, age) { console.log(name) console.log(age) console.log(this.value); } bar.call2(foo, 'black', '18') // black 18 1
还有一点须要注意的是,若是不传入参数,默认指向为 window,因此最终版代码:对象
Function.prototype.call2 = function(context) { var context = context || window context.fn = this // this 也就是调用call的函数 var args = [...arguments].slice(1) var result = context.fn(...args) delete context.fn() return result } var value = 1 function bar() { console.log(this.value) } bar.call2()
apply
的方法和 call
方法的实现相似,只不过是若是有参数,以数组形式进行传递,直接上代码:ip
Function.prototype.apply2 = function(context) { var context = context || window context.fn = this // this 也就是调用apply的函数 var result // 判断是否有第二个参数 if(arguments[1]) { result = context.fn(...arguments[1]) } else { result = context.fn() } delete context.fn() return result } var foo = { value: 1 } function bar(name, age) { console.log(name) console.log(age) console.log(this.value); } bar.apply2(foo, ['black', '18']) // black 18 1