欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javascript中call apply 与 bind方法详解

程序员文章站 2022-06-29 22:42:49
在javascript中,call、apply和bind是function对象自带的三个方法,本文将通过几个场景的应用,来详细理解三个方法。 call() call...

在javascript中,call、apply和bind是function对象自带的三个方法,本文将通过几个场景的应用,来详细理解三个方法。

call()

call() 方法在使用一个指定的this值和若干个指定的参数值的前提下调用某个函数或方法。

当调用一个函数时,可以赋值一个不同的 this 对象。this 引用当前对象,即 call 方法的第一个参数。

通过 call 方法,你可以在一个对象上借用另一个对象上的方法,比如object.prototype.tostring.call([]),就是一个array对象借用了object对象上的方法。

语法 fun.call(thisarg[, arg1[, arg2[, ...]]])
thisarg
在fun函数运行时指定的this值。需要注意的是下面几种情况

(1)不传,或者传null,undefined, 函数中的this指向window对象
(2)传递另一个函数的函数名,函数中的this指向这个函数的引用,并不一定是该函数执行时真正的this值
(3)值为原始值(数字,字符串,布尔值)的this会指向该原始值的自动包装对象,如 string、number、boolean
(4)传递一个对象,函数中的this指向这个对象

arg1, arg2, ...
指定的参数列表。

例子
初级应用例子

function a(){
 //输出函数a中的this对象
 console.log(this); 
}
//定义函数b
function b(){} 

var obj = {name:'这是一个屌丝'}; //定义对象obj
a.call(); //window
a.call(null); //window
a.call(undefined);//window
a.call(1); //number
a.call(''); //string
a.call(true); //boolean
a.call(b);// function b(){}
a.call(obj); //object

使用call方法调用匿名函数并且指定上下文的this

在下面的例子中,当调用 greet 方法的时候,该方法的 this 值会绑定到 i对象。

function greet() {
 var reply = [this.person, '是一个轻量的', this.role].join(' ');
 console.log(reply);
}

var i = {function greet() {
 var reply = [this.person, '是一个轻量的', this.role].join(' ');
 console.log(reply);
}

var i = {
 person: 'jslite.io', role: 'javascript 库。'
};

greet.call(i); 
// jslite.io 是一个轻量的 javascript 库。


 person: 'jslite.io', role: 'javascript 库。'
};

greet.call(i); 
// jslite.io 是一个轻量的 javascript 库。

使用call方法调用匿名函数

在下例中的for循环体内,我们创建了一个匿名函数,然后通过调用该函数的call方法,将每个数组元素作为指定的this值执行了那个匿名函数。这个匿名函数的主要目的是给每个数组元素对象添加一个print方法,这个print方法可以打印出各元素在数组中的正确索引号。当然,这里不是必须得让数组元素作为this值传入那个匿名函数(普通参数就可以),目的是为了演示call的用法。

var animals = [
 {species: 'lion', name: 'king'},
 {species: 'whale', name: 'fail'}
];

for (var i = 0; i < animals.length; i++) {
 (function (i) { 
 this.print = function () { 
 console.log('#' + i + ' ' + this.species + ': ' + this.name); 
 } 
 this.print();
 }).call(animals[i], i);
}
//#0 lion: king
//#1 whale: fail

使用call方法调用函数传参数

var a = {
 name:'jslite.io', //定义a的属性
 say:function(){ //定义a的方法
 console.log("hi,i'm function a!");
 }
};
function b(name){
 console.log("post params: "+ name);
 console.log("i'm "+ this.name);
 this.say();
}

b.call(a,'test');
//post params: test
//i'm onepixel
//i'm function a!

apply()

语法与 call() 方法的语法几乎完全相同,唯一的区别在于,apply的第二个参数必须是一个包含多个参数的数组(或类数组对象)。apply的这个特性很重要,

在调用一个存在的函数时,你可以为其指定一个 this 对象。 this 指当前对象,也就是正在调用这个函数的对象。 使用 apply, 你可以只写一次这个方法然后在另一个对象中继承它,而不用在新对象中重复写该方法。

语法:fun.apply(thisarg[, argsarray])
注意: 需要注意:chrome 14 以及 internet explorer 9 仍然不接受类数组对象。如果传入类数组对象,它们会抛出异常。

参数
thisarg

同上call 的thisarg参数。

argsarray

一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 fun 函数。如果该参数的值为null 或 undefined,则表示不需要传入任何参数。从ecmascript 5 开始可以使用类数组对象。

例子

function jsy(x,y,z){
 console.log(x,y,z);
}

jsy.apply(null,[1,2,3]); 
// 1 2 3

使用apply来链接构造器的例子

你可以使用apply来给一个对象链接构造器,类似于java. 在接下来的例子中我们会创建一个叫做construct的全局的function函数,来使你能够在构造器中使用一个类数组对象而非参数列表。

function.prototype.construct = function(aargs) {
 var fconstructor = this, 
 fnewconstr = function() { 
 fconstructor.apply(this, aargs); 
 };
 fnewconstr.prototype = fconstructor.prototype;
 return new fnewconstr();
};
function myconstructor () {
 for (var nprop = 0; nprop < arguments.length; nprop++) {
 console.log(arguments,this)
 this["property" + nprop] = arguments[nprop];
 }
}
var myarray = [4, "hello world!", false];
var myinstance = myconstructor.construct(myarray);

console.log(myinstance.property1);  // logs "hello world!"
console.log(myinstance instanceof myconstructor); // logs "true"
console.log(myinstance.constructor);  // logs "myconstructor"

使用apply和内置函数

聪明的apply用法允许你在某些本来需要写成遍历数组变量的任务中使用内建的函数。在接下里的例子中我们会使用math.max/math.min来找出一个数组中的最大/最小值。

//里面有最大最小数字值的一个数组对象
var numbers = [5, 6, 2, 3, 7];

/* 使用 math.min/math.max 在 apply 中应用 */
var max = math.max.apply(null, numbers);
// 一般情况是用 math.max(5, 6, ..) 或者 math.max(numbers[0], ...) 来找最大值
var min = math.min.apply(null, numbers);

//通常情况我们会这样来找到数字的最大或者最小值
//比对上面的栗子,是不是下面的看起来没有上面的舒服呢?
max = -infinity, min = +infinity;
for (var i = 0; i < numbers.length; i++) {
 if (numbers[i] > max)
 max = numbers[i];
 if (numbers[i] < min) 
 min = numbers[i];
}

参数数组切块后循环传入

function minofarray(arr) {
 var min = infinity;
 var quantum = 32768;

 for (var i = 0, len = arr.length; i < len; i += quantum) {
 var submin = math.min.apply(null, arr.slice(i, math.min(i + quantum, len)));
 console.log(submin, min)
 min = math.min(submin, min);
 }

 return min;
}

var min = minofarray([5, 6, 2, 3, 7]);


bind

bind() 函数会创建一个新函数(称为绑定函数)

bind是es5新增的一个方法
传参和call或apply类似
不会执行对应的函数,call或apply会自动执行对应的函数
返回对函数的引用
语法 fun.bind(thisarg[, arg1[, arg2[, ...]]])

下面例子:当点击网页时,eventclick被触发执行,输出jslite.io p1 p2, 说明eventclick中的this被bind改变成了obj对象。如果你将eventclick.bind(obj,'p1','p2') 变成 eventclick.call(obj,'p1','p2') 的话,页面会直接输出 jslite.io p1 p2

var obj = {name:'jslite.io'};
/**
 * 给document添加click事件监听,并绑定eventclick函数
 * 通过bind方法设置eventclick的this为obj,并传递参数p1,p2
 */
document.addeventlistener('click',eventclick.bind(obj,'p1','p2'),false);
//当点击网页时触发并执行
function eventclick(a,b){
 console.log(
  this.name, //jslite.io
  a, //p1
  b //p2
 )
}
// jslite.io p1 p2

兼容

if (!function.prototype.bind) {
 function.prototype.bind = function (othis) {
 if (typeof this !== "function") {
 // closest thing possible to the ecmascript 5
 // internal iscallable function
 throw new typeerror("function.prototype.bind - what is trying to be bound is not callable");
 }

 var aargs = array.prototype.slice.call(arguments, 1), 
 ftobind = this, // this在这里指向的是目标函数
 fnop = function () {},
 fbound = function () {
  return ftobind.apply(this instanceof fnop
   ? this //此时的this就是new出的obj
   : othis || this,//如果传递的othis无效,就将fbound的调用者作为this
  
  //将通过bind传递的参数和调用时传递的参数进行合并,并作为最终的参数传递
  aargs.concat(array.prototype.slice.call(arguments)));
 };
 fnop.prototype = this.prototype;
 //将目标函数的原型对象拷贝到新函数中,因为目标函数有可能被当作构造函数使用
 fbound.prototype = new fnop();
 //返回fbond的引用,由外部按需调用
 return fbound;
 };
}

兼容例子来源于:https://developer.mozilla.org/zh-cn/docs/web/javascript/reference/global_objects/function/bind#compatibility

应用场景:继承

function animal(name,weight){
 this.name = name;
 this.weight = weight;
}
function cat(){
 // 在call中将this作为thisargs参数传递
 // animal方法中的this就指向了cat中的this
 // 所以animal中的this指向的就是cat对象
 // 在animal中定义了name和weight属性,就相当于在cat中定义了这些属性
 // cat对象便拥有了animal中定义的属性,从而达到了继承的目的
 animal.call(this,'cat','50');
 //animal.apply(this,['cat','50']);
 this.say = function(){
 console.log("i am " + this.name+",my weight is " + this.weight);
 }
}
//当通过new运算符产生了cat时,cat中的this就指向了cat对象
var cat = new cat();
cat.say();
//输出=> i am cat,my weight is 50

原型扩展

在原型函数上扩展和自定义方法,从而不污染原生函数。例如:我们在 array 上扩展一个 foreach

function test(){
 // 检测arguments是否为array的实例
 console.log(
 arguments instanceof array, //false
 array.isarray(arguments) //false
 );
 // 判断arguments是否有foreach方法
 console.log(arguments.foreach); 
 // undefined
 // 将数组中的foreach应用到arguments上
 array.prototype.foreach.call(arguments,function(item){
 console.log(item); // 1 2 3 4
 });
}
test(1,2,3,4);