对call,apply的理解

首先先说明它们共同的作用:call和apply 都是用来修改函数中this的指向问题;

其次就是它们不同的传参方式:注意上一句话中说他们的作用时有两个关键词 ‘函数’和‘this’,想要修改this 的指向,那么必然有一个this修改后的指向,而函数必然后关系到传参问题:call方法可以传给该函数的参数分别作为自己的多个参数,而apply方法必须将传给该函数的参数合并成一个数组作为自己的一个参数:

var name = 'Evan';
var age = 20;
var person = {
    name: 'Hillary',
    age: 19,
    sayIntroduce: function () {
        return "Hello, My name is " + this.name + " and I'm " + this.age + ' years old.'
    },
    sayHobby: function (val1, val2) {
        return "I'm " + this.name + ", I like " + val1 + " and " + val2 + ".";
    }
}
var person1 = {
    name: 'Coy'
}
console.log(person.sayIntroduce()); // Hello, My name is Hillary and I'm 19 years old.

当我们通过 call 和 apply 来this的指向时,不传任何参数,则默认为将this指向修改为 windows

// 当没有参数时,默认将this指向 window
 console.log(person.sayIntroduce.call()); // Hello, My name is Evan and I'm 20 years old.
 console.log(person.sayIntroduce.apply()); // Hello, My name is Evan and I'm 20 years old.

有参数时,this 指向第一个参数:

// 将this指向 person1,由于person1中没有age属性,因此为 undefined
console.log(person.sayIntroduce.call(person1)); // Hello, My name is Coy and I'm undefined years old.
console.log(person.sayIntroduce.apply(person1)); // Hello, My name is Coy and I'm undefined years old.

当需要传递参数时,call可以直接写多个参数,apply需要用数组方式传递:

console.log(person.sayHobby.call(person1, 'swimming', 'hiking')); // I'm Coy, I like swimming and hiking.
console.log(person.sayHobby.apply(person1, ['swimming', 'hiking'])); // I'm Coy, I like swimming and hiking.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 3,272评论 0 4
  • 函数和对象 1、函数 1.1 函数概述 函数对于任何一门语言来说都是核心的概念。通过函数可以封装任意多条语句,而且...
    道无虚阅读 4,665评论 0 5
  • 大家好,我是IT修真院萌新分院第3期的学员张晓琳,一枚正直、纯洁、善良的前端程序员今天给大家分享一下,修真院官网j...
    Demon_0481阅读 584评论 0 2
  • 在JavaScript编程中,this关键字总是让初学者感到迷惑,Function.prototype.call和...
    yufawu阅读 413评论 0 7
  • 文/熠歆 早安! 美好的一天就从这顿早餐开始! 五谷杂粮粥配方: 黑米,紫米,高粱米,燕麦,小麦仁,糙米 方法: ...
    熠歆阅读 388评论 0 8