call()
方法在使用一個指定的this
值和若干個指定的參數值
的前提下調用
某個函數或方法
function foo (){ console.log(this.name) } var obj = { name:'xiaoming' } foo.call(obj) // xiaoming
從前面簡單的例子中得出幾點:git
那是否是能夠簡單的理解成,我在這個對象中添加了一個屬性,並執行:github
var obj ={ name:'xiaoming', fn:function(){ console.log(this.name) } } // this 指向的是 obj console.log(obj.fn()) // xiaoming
根據上面的思路能夠完善一下:數組
Function.prototype.call1 = function (context) { // this指向調用 call1方法的函數,將這個函數賦值給 fn,也就是上面說到的給 obj添加一個 fn 方法 context.fn = this // 執行這個方法 context.fn() //咱們不能無緣無故的給一個對象添加多餘的屬性,因此要把這個屬性再刪除掉 delete context.fn }
call()
還能給定參數執行函數
Function.prototype.call2 = function(context){ context.fn = this var arg = [] // 從第二個參數開始取 for(i=1;i<arguments.length;i++){ arg.push(arguments[i]) } // 將值傳給要執行的函數 context.fn(...arg) delete context.fn }
this 參數能夠爲null
,當參數值爲 null 時,this 指向的是window
Function.prorotype.call3 = function (context) { //判斷參數 context 是否爲 null var context = context || window context.fn = this var arg = [] for(var i = 1;i<arguments.length;i++){ arg.push(arguments[i]) } context.fn(...arg) delete context.fn }
函數是能夠有返回值的!
小栗子:app
var obj = { value:1 } function foo (name,age){ console.log(name) console.log(age) console.log(this.value) } foo.call(obj,"ann",18) // ann // 18 // 1
那麼能夠進行最後的完善啦~函數
Function.prototype.call4 = function(context){ var context = context || window context.fn = this var arg = [] for (var i = 1; i<arguments.length; i++) { arg.push(arguments[i]) } var result = context.fn(...arg) delete context.fn return result }
apply()
方法和call()
方法用法很類似
var obj = { value: 'value' } function foo(name, age) { console.log(name) console.log(age) console.log(this.value) } foo.apply(obj, ['ken', 18]) // ken // 18 // value
實現 apply 方法:this
Function.prototype._apply = function (context,arr) { context = context || window context.fn = this var result if(!arr){ result = context.fn() }else{ var arg = [] for(var i = 0;i<arr.length;i++){ arg.push(arr[i]) } result = context.fn(...arg) } delete context.fn return result }
https://github.com/mqyqingfen...prototype