技术分享 Technology to share

理解JS中的call、apply、bind方法

bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。

下面就以这两个函数为例

function one(){
  console.log('name',this.name)
  console.log('value','one')
}

function two(){
  console.log('name',this.name)
  console.log('value','two')
}
one()
// name undefined
// value one
two()
// name undefined
// value two
one.apply(one)
// name one
// value one
one.apply(two)
// name two
// value one
function printThis(){
  console.log(this)
}

printThis.apply();   //window
printThis.apply(null);   //window
printThis.apply(undefined);   //window
printThis.apply(1);   //Number
printThis.apply('');   //String
printThis.apply(true);   //Boolean

apply、call 二者而言,作用完全一样,只是接受参数的方式不太一样。

bind 和其他两者最大区别就是不会立即执行 而是返回一个函数

viod call(thisArg,...argArray)
viod apply(thisArg,?argArray)
Function bind(thisArg,...argArray)

上一篇: three 局部辉光

下一篇: 相似图片搜索

分享到以下平台: