call() / apply() / bind() 的区别和作用

bind call apply改变函数中this指向的区别

  JS中这三个都是用来改变this指向问题的,都是跟在函数的后面;他们的第一个参数都是你想要指定的this对象;都可以接受传参。

  最大的区别:

    call和apply都是直接调用函数,返回值就是调用的函数的返回值;而bind不会调用函数,他会返回一个新的函数

    你必须在bind后面再加一个括号才能执行

  传参的区别:

    apply接收两个参数,第二个参数是一个数组,调用后里面的值会自动的展开类似于数组转字符串

    call和bind可以接受多个参数,除了一个是this指向外,其余的参数对应函数的参数。

根据这哥三儿的特点就有了以下用处:

利用apply()求最大值

console.log(Math.max.apply([],[2,6,8,3,4,9,7,23,56,889])) // 利用 apply() 会展开第二个参数的特性,效果等同于 ...[1,2,3] 展开运算符

利用call()判断数据类型

console.log(Object.prototype.toString.call("qq"))            // [object String] 返回值都是字符串类型
console.log(Object.prototype.toString.call(12))              // [object Number]
console.log(Object.prototype.toString.call(false))           // [object Boolean]
console.log(Object.prototype.toString.call(undefined))       // [object Undefined]
console.log(Object.prototype.toString.call(null))            // [object Null]
console.log(Object.prototype.toString.call(function(){}))    // [object Function]
console.log(Object.prototype.toString.call([]))              // [object Array]
console.log(Object.prototype.toString.call({}))              // [object Object]

call继承

function Person(name,age){
  this.name = name;
  this.age = age;
}
function Coder(name,age,job){
  Person.call(this,name,age);
  this.job = job;
  // console.log(this);//Coder
}
let p = new Person('成龙',58);
let c = new Coder('房祖名',26,'演员');

console.log(c);//Coder {name: "房祖名", age: 26, job: "演员"}
console.log(p);//Person {name: "成龙", age: 58}
原文地址:https://www.cnblogs.com/MrZhujl/p/13038344.html