美文网首页
改变函数内部this的指向

改变函数内部this的指向

作者: 时间的溺水者 | 来源:发表于2020-05-09 14:50 被阅读0次

js中可以利用call、apply、bind改变函数内部this的指向

1、call方法

call()方法调用一个对象,简单理解为调用函数的方法、但是它可以改变函数this的指向

call()方法调用一个对象,简单理解为调用函数的方法、但是它可以改变函数this的指向

func.call(thisArg, arg1, arg2, ...)

let o = {
  name: 'andy'
}

function fn () {
  console.log(`我的名字叫${this.name}`)
}

fn.call(o) // 我的名字叫andy

call的作用:
1、调用函数
2、改变函数内的this指向
3、可以实现继承

2、apply方法

func.apply(thisArg, [arg1, arg2, ...])

let o = {
  name: 'andy'
}

function fn (arr) {
  console.log(`我的名字叫${this.name}`)
  console.log(arr) // 'pink'
}

fn.apply(o, ['pink']) // 我的名字叫andy

1、调用函数
2、改变函数内的this指向,不需要改变时,第一个参数传入null
3、参数是数组形式(伪数组)

apply的应用

求数组最值

let arr = [1, 4, 6]

Math.max.apply(Math, arr) // 6
Math.min.apply(Math, arr) // 1

bind

bind()方法不会调用方法,但是可以改变函数内部this的指向

func.bind(thisArg, arg1, arg2, ...)

thisArg 在func函数运行时指定的this值
arg1, arg2 传递参数
不会执行函数但返回由指定的this值和初始化参数改变的原函数拷贝

let o = {
  name: 'andy'
}

function fn () {
  console.log(`我的名字叫${this.name}`)
}

let f = fn.bind(o)

f()
有时候不需要立即调用,但是又想改变函数内部this的指向,可以用bind

例如有个按钮点击之后就禁用,3s之后开启这个按钮

let btn = document.getSelector('button')

btn.onclick = function () {
  this.disabled = true
  setTimeout(function() {
    this.disabled = false
  }.bind(this), 3000) // 这个this指向btn这个对象
}

相关文章

  • this指针

    (1)普通函数中的this指向:this指向普通函数中的调用者; 通过call和apply改变函数内部this的指向:

  • javascript之函数

    函数内部this的指向的几种情况 改变函数内部的this(call、bind、apply的区别) 函数基础 创建和...

  • this、call、apply、bind

    this的指向(this永远指向最后调用它的那个对象) 改变this指向 ES6函数箭头 在函数内部使用 var...

  • 详解如何实现call/apply/bind

    call、apply 及 bind 函数内部实现是怎么样的? 一、call call改变了this指向 函数执行 ...

  • 函数调用方式&图书管理操作&严格模式&作用域&变量提升

    函数调用方式 普通构造函数调用:内部的this指向全局对象window; 构造函数调用:内部的this指向新创建的...

  • this apply call bind

    怎么改变 this 的指向 1、使用 ES6 的箭头函数 2、在函数内部使用_this = this 3、使用ap...

  • 改上下文-js-v1.0.0

    #什么是它? 改变某个函数运行时的上下文(context)。换句话说,改变函数体内部 this 的指向。 #如何实...

  • JavaScript的this(三)call,apply,bin

    使用bind,apply,call改变函数中this的指向 首先先举个例子 向上面这样直接执行函数,函数内部的th...

  • apply call bind

    apply call bind 的区别 apply,call的存在是为了改变函数体内部this的指向,改变作用域的...

  • 详解 JS 函数的 call、apply 及 bind 方法

    ?总结 相同点都能够改变目标函数执行时内部 this 的指向方法的第一个参数用于指定函数执行时内部的 this 值...

网友评论

      本文标题:改变函数内部this的指向

      本文链接:https://www.haomeiwen.com/subject/avhjnhtx.html