小學生都能理解的原生js——call

關於 js 做用域和執行上下文就不過多介紹了,本人也是在網上搜集了各類教程才逐漸理解,如下簡單理解並說下call 的做用數組

首先簡單理解下執行上下文有關概念,this 的指向就表明當前執行環境的上下文app

function Person(name){
    this.name = name,
    this.speak = function(){
        console.log('my name is ' + this.name)
    }
}
var p = new Person('張三');
p.speak()

這裏的this 就指new出來的對象,調用這個方法的對象函數

 

call 簡單的來講是改變this的執行上下文環境,改變this 的指向對象,把以前指向 pet 的this 指向了dog對象,因此this 的words屬性 變成了dog 對象的屬性。後面跟着的參數是執行函數的參數列表,apply 用法相同,後面的參數是參數數組this

var pet = {
    words:'hello',
    speak:function(say){
        console.log(say + ' ' + this.words)
    }
}

var dog = {
    words:'wang'
}

pet.speak('說話')

pet.speak.call(dog,'叫')
相關文章
相關標籤/搜索