函数中this的指向问题

本文详细讲解了JavaScript中this在普通函数、定时器、构造函数、原型方法以及对象方法中的指向,并介绍call、apply和bind等方法如何改变this的指向。通过实例演示,理解this在不同情境下的行为并提升代码灵活性。
摘要由CSDN通过智能技术生成

1、常见的情形中this的指向

函数中的this指向分以下几类情况:
在这里插入图片描述

  • 普通函数中的this
/**
 * 普通函数中的this: window
 */
function testQuery(){
   console.dir(this);
}
  • 定时器方法中的this
/**
 * 普通函数中的this: window
 */
setInterval(function (){
 console.dir(this);
}, 1000);
  • 构造函数中的this
/**
 * 构造函数中的this: 实例对象
 */
function Person(){
  console.dir(this);
}
var per = new Person();
  • 原型对象方法中的this
/**
 * 原型对象方法中的this:实例对象
 */
Person.prototype.eat = function (){
  console.dir(this);
};
per.eat();
  • 普通函数中的this
/**
* 对象.方法中的this:实例对象
*/

2、如何改变this的指向

为了使用某种特定环境的 this 引用, JavaScript 为我们专门提供了一些函数方法用来帮我们更优雅的处理函数内部 this 指向问题,包括 call、apply、bind 三个函数。

  • call
    基本语法:fun.call(thisArg[, arg1[, arg2[, …]]])
thisArg  –The value to use as this when calling func. 调用方法时this实际指向
arg1, arg2, ...argN  – Arguments for the function. 调用方法的入参
  • apply
    基本语法:fun.apply(thisArg, [argsArray])
thisArg  –The value to use as this when calling func. 调用方法时this实际指向
argsArray – An array-like object, specifying the arguments with which func should be called. 调用方法的入参

例:

function Person(age){
    this.age = age;
}

Person.prototype.sayHi = function (x, y){
  console.log((x + y) + " ==== " + this.age);
};

function Student(age){
    this.age = age;
}

var person = new Person(10);
var student = new Student(20);

//	apply和call,第一个参数代表this的实际指向,第二个参数代表调用方法时的实参
//	不同之处:apply的第二个参数是数组,call的第二个参数是可变参数列表
person.sayHi.apply(student, [10, 60]);
person.sayHi.call(student, 10, 60);
  • bind
    基本语法:bind(thisArg[, arg1[, arg2[, …]]])
    对于一个给定的函数,bind会创建一个和原始函数一样的函数,这个新创建的函数的this对象会绑定到bind(thisArg, args)的第一个参数thisArg上,且这个函数具有args这些参数。
    返回值是一个函数。
/**
 *  bind 赋值一份函数,并绑定到指定的对象,可以改变this的指向
 *
 *  函数名.bind(对象, 参数1, 参数2, ...)
 *    返回的是复制后的函数
 *
 */
function Person(age){
  this.age = age;
}

Person.prototype.sayHi = function (){
  console.log("sayHi...");
};

function Student(age){
  this.age = age;
}

var person = new Person(10);
var student = new Student(20);

/**
 * For a given function, creates a bound function that has the same body as the original function.
 * The this object of the bound function is associated with the specified object, and has the specified initial parameters.
 * @param thisArg The object to be used as the this object.
 * @param args Arguments to bind to the parameters of the function.
 */
//  复制一份
var ff = person.sayHi.bind(student);
ff();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值