JS中的this、apply、call、bind

一、this

在JavaScript中this可以是全局对象、当前对象或者任意对象,这完全取决于函数的调用方式,this 绑定的对象即函数执行的上下文环境(context)。
eg:

var person = {
  name: 'aaa',
  describe: function () {
    return this.name;
  }
};
console.log(person.describe()) // aaa   函数的执行环境为person,所以this指向person
var A = {
  name: 'aaa',
  describe: function () {
    return this.name;
  }
};
var B = {
  name: 'bbb'
};
B.describe = A.describe;
console.log(B.describe()) // bbb    执行环境为B
var name = "windowsName";
function a() {
  var name = "Demi";
  console.log(this.name);          // windowsName
  console.log("inner:" + this);    // inner:[object Window]
}
a();  //执行环境为window
console.log("outer:" + this); 
var name = 'window'
var person = {
  name: 'aaa',
  describe: function () {
    return this.name;
  }
};
var f = person.describe;
console.log(f()) // window
var name = "windowsName";
function fn() {
 var name = 'Cherry';
 innerFunction();
 function innerFunction() {
  console.log(this.name);  // windowsName
 }
}
fn()

二、改变this指向

2.1 call

call(context, arg1,arg1...)

var person = {
 fullName: function (arg1, arg2) {
   return arg1 + ' ' + this.firstName + " " + this.lastName + ' ' + arg2;
 }
}
var person1 = {
 firstName: "Bill",
 lastName: "Gates",
}
var person2 = {
 firstName: "Steve",
 lastName: "Jobs",
}
person.fullName.call(person1, 'Hello', 'Bye!');  // 将返回 "Hello Bill Gates Bye!"
person.fullName.call(person2, 'Hello', 'Bye!');  // 将返回 "Hello Steve Jobs Bye!"

2.2 apply

apply和call用法相似,只有传参方式不同。call() 方法分别接受参数,apply() 方法接受数组形式的参数。如果要使用数组而不是参数列表,则 apply() 方法非常方便。

person.fullName.apply(person1, ['Hello', 'Bye!']);  // 将返回 "Hello Bill Gates Bye!"

2.3 bind

和call用法一样,但是call和apply都是改变函数的指向,并立即调用函数。
this方法不会立即执行,而是返回一个改变了上下文 this 后的函数,原函数的 this 并没有被改变。

function fn(a, b, c) {
    console.log(a, b, c);
}
var fn1 = fn.bind(null, 'Dot');

fn('A', 'B', 'C');            // A B C
fn1('A', 'B', 'C');           // Dot A B
fn1('B', 'C');                // Dot B C
fn.call(null, 'Dot');      // Dot undefined undefined

call 是把第二个及以后的参数作为 fn 方法的实参传进去,而 fn1 方法的实参实则是在 bind 中参数的基础上再往后排。

三、使用场景

  1. 求数组的最大值或最小值
Math.max(1,2,3,4,5,1,2,3) // 5
var arr = [1,2,3,89,46]
var max = Math.max.apply(null,arr)//89
var min = Math.min.apply(null,arr)//1
  1. 将类数组转化为数组
var trueArr = Array.prototype.slice.call(arrayLike)
  1. 数组追加
var arr1 = [1,2,3];
var arr2 = [4,5];
var total = [].push.apply(arr1, arr2);
console.log(arr1) //[1, 2, 3, 4, 5]
console.log(arr2) //[4,5]
  1. 利用call和apply做继承
function Person(name, age) {
  // 这里的this都指向实例
  this.name = name
  this.age = age
}
function Female() {
  Person.apply(this, arguments)
}
var dot = new Female('Amy', 25)

你可能感兴趣的:(JS中的this、apply、call、bind)