js修改函数this

一、js修改函数的this指向有三种方法(关于他们的区别字体加粗):
  1. apply:调用函数并且修改函数this指向;返回值就是函数的返回值;函数传递参数以数组的形式传递;常用于Math内置对象对数组求最大最小值;
const o ={}
// 1. apply
function fun(a,b) {
    console.log(this,a,b)
    return 'apply'
}
let result = fun.apply(o,[1,2])
console.log(result)
// 应用
console.log(Math.max.apply(Math, [3,2,7,8]))
{} 1 2
apply
8
  1. call:调用函数并且修改函数this指向;返回值就是函数的返回值;函数的参数以逗号分隔的形式传递;常用于构造函数组合方式继承;
const o1 ={}
function fun1(a,b) {
    console.log(this,a,b)
    return 'call'
}
let result1 = fun1.call(o1,1,2)
console.log(result1)
{} 1 2
call
  1. bind:不调用函数但是可以修改函数this指向;返回的值是一个新函数(并且新函数在调用的到时候不需要在传递实参,因为在调用bind方法就已经在内部处理了这些实参,我们只需要调用新函数这些实参会自动传递给形参);函数的参数以逗号分隔的形式传递;常用于修改定时器的this指向;
const o2  ={
    len: 1
}
let len = 100
function fun2(a,b) {
    console.log(this,a,b)
}
const f = fun2.bind(o2,1,2)
f()
setTimeout(function (a,b) {
    console.log(this.len,a,b)
}.bind(o2,1,2),2000)
{ len: 1 } 1 2
1 1 2
二、当apply、call、bind方法第一个参数为值类型时
  1. 非严格模式下
 // 非严格模式下
    function fun() {
        console.log(this)
    }
    // 1. undefined / null    ----->   Window
    fun.apply(undefined) // Window
    fun.apply(null) // Window
    fun.call(undefined) // Window
    fun.call(null) // Window
    fun.bind(undefined)() // Window
    fun.bind(null)() // Window

//    2. number / boolean / string     ------>  本身构造函数的实例对象
    fun.apply(10)  // Number {10}
    fun.apply(true) // Boolean {true}
    fun.apply('str') // String {"str"}
    fun.call(10) // Number {10}
    fun.call(true) // Boolean {true}
    fun.call('str') // String {"str"}
    fun.bind(10)() // Number {10}
    fun.bind(true)() // Boolean {true}
    fun.bind('str')() // String {"str"}
  1. 严格模式下
//    严格模式下

    // null / undefined / number / string / boolean   ------>   值本身

    'use strict'
    function f() {
        return this
    }
    console.log(f.apply(null),f.apply(undefined),f.apply(10),f.apply('str'),f.apply(true)) // null undefined 10 "str" true
    console.log(f.call(null),f.call(undefined),f.call(10),f.call('str'),f.call(true)) // null undefined 10 "str" true
    console.log(f.bind(null)(),f.bind(undefined)(),f.bind(10)(),f.bind('str')(),f.bind(true)()) // null undefined 10 "str" true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值