bind, call, apply all about 'thi

2019-08-05  本文已影响0人  meteornnnight

bind:

bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被bind的第一个参数指定,其余的参数将作为新函数的参数供调用时使用。
也就是说,func.bind(obj)返回一个新函数,新函数的this指向obj
Example:

var func=function(){
  console.log(this.name);
}
const obj={name: "amy"};
const obj1{name: "leo"};
func.bind(obj)(); //output "amy"
func.bind(obj1)(); //output "leo"
// besides
func.bind(obj).apply(obj1); //output "amy"

func.bind(obj).apply(obj1); //output "amy",意味bind return的函数中的this已经被绑定,无法通过apply改变了。

apply:

apply的第一个参数同样是决定函数内部this指向的object,之后的参数则为数组或者类数组,数组中的每个元素都会被函数接受为argument/parameter.

example 1:
var fruit=['apple','grape'];
var moreFruit=['orange','watermelon'];
Array.prototype.push(fruit, moreFruit);
//equals to Array.prototype.push(fruit,'orange','watermelon');

其实apply就是把函数能接受的所有参数都打包在了一个数组或者类数组里传给函数了

example 2: 如何利用apply, Math.min不用loop,求一个超级大的数组中的最小值。

因为js引擎对函数接受的参数个数有限制,所以我们尽量避免把一个特别大的数组全部通过apply传进Math.min中,而是分次传进它的子数组。

var min=Infinity;
var subLength=5000;
for(var i=0,len=arr.length;i<len;i+=subLength){
min=Math.min(min, Math.min.apply(null, arr.slice(i, Math.min(i+subLength, len) ) ) );
}
console.log(min);

上述代码中考虑到了避免数组下标越界的问题,Array.prototype.slice(begin,end)取的是[begin,end-1]的元素们。

call:

callapply一样,都可以改变函数内部this的指向。利用call, 可以在构造函数内部调用别的class的构造函数,类似java中的super()
Example:

function Person(name,id){
  this.name=name;
  this.id=id;
}
function Employee(name,id,salary){
  Person.call(this,name,id);
  this.salary=salary;
}
console.log(new Employee("mike", 213, 13000).name);```
上一篇 下一篇

猜你喜欢

热点阅读