call()与apply()简单介绍

来源:互联网 发布:bi li哔哩哔哩mac 编辑:程序博客网 时间:2024/06/10 03:17

call 和 apply 都是为了动态改变某个函数运行时的上下文而存在的,即改变函数体内部 this 的指向。call 和 apply 主要的区别在于他们的声明方式不同。call 需要参数分开传递,而 apply 需要传入由参数组成的数组。
ep:

function people() {} people.prototype = {    say: function() {      alert("hell word");    }}var student = new people();student.say(); //hello worldstudent2 = {};  //没有say()方法student.say.call(student2);  //hello worldstudnet.say.apply(student2);  //此时的student2可以使用say()方法

(1).传递参数
ep:

function sum(x,y) {    return x+y;}function call1(num1,num2) {    return sum.call(this,num1,num2);}function apply1(num1,num2) {    return sum.apply(this,[num1,num2]);  //参数为数组形式}

(2).改变函数运行的作用域

window.color = 'red';var obj = {color: 'blue'};function showColor() {    alert(this.color);  }showColor.call(this);  //redshowColor.call(obj);  //blue
0 0
原创粉丝点击