一、js修改函数的this指向有三种方法(关于他们的区别字体加粗):
apply:调用函数并且修改函数this指向;返回值就是函数的返回值;函数传递参数以数组的形式传递 ;常用于Math内置对象对数组求最大最小值;
const o = { }
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
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
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方法第一个参数为值类型时
非严格模式下
function fun ( ) {
console. log ( this )
}
fun . apply ( undefined )
fun . apply ( null )
fun . call ( undefined )
fun . call ( null )
fun . bind ( undefined ) ( )
fun . bind ( null ) ( )
fun . apply ( 10 )
fun . apply ( true )
fun . apply ( 'str' )
fun . call ( 10 )
fun . call ( true )
fun . call ( 'str' )
fun . bind ( 10 ) ( )
fun . bind ( true ) ( )
fun . bind ( 'str' ) ( )
严格模式下
'use strict'
function f ( ) {
return this
}
console. log ( f . apply ( null ) , f . apply ( undefined ) , f . apply ( 10 ) , f . apply ( 'str' ) , f . apply ( true ) )
console. log ( f . call ( null ) , f . call ( undefined ) , f . call ( 10 ) , f . call ( 'str' ) , f . call ( true ) )
console. log ( f . bind ( null ) ( ) , f . bind ( undefined ) ( ) , f . bind ( 10 ) ( ) , f . bind ( 'str' ) ( ) , f . bind ( true ) ( ) )