好好學習-JS基礎-call/apply實現

call

call()方法在使用一個指定的 this 值和 若干個指定的參數值的前提下 調用某個函數或方法
function foo (){
    console.log(this.name)
}
var obj = {
    name:'xiaoming'
}

foo.call(obj)  // xiaoming

從前面簡單的例子中得出幾點:git

  • call 函數改變了 this 的指向,this 指向了 obj
  • 執行了 foo 這個函數

那是否是能夠簡單的理解成,我在這個對象中添加了一個屬性,並執行: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

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

  • 改變 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

相關文章
相關標籤/搜索