JavaScript 的 this 和 apply call bind

this 是谁

1,this 在函数运行时才肯定
2,谁挪用了函数谁就是 this
3,this 就是挪用者

比方

var o1 = {
  name: 'o1',
}
var o2 = {
  name: 'o2',
}
o1.hello = function() {
  console.log('this 是,', this)
}
o2.hello = function() {
  console.log('this 是, ', this)
}
o1.hello()
o2.hello() 

《JavaScript 的 this 和 apply call bind》

o1 挪用了 hello 函数,所以 hello 函数中的 this 就是 o1(挪用者是 o1
o2 同理

什么是全局对象

1,浏览器的全局对象是 window
2,node.js 中全局对象是 global

在浏览器中直接挪用一个函数,那末 this 就是 window (挪用者是 window

比方

var hello = function() {
  console.log('this 是,', this)
}
hello()

《JavaScript 的 this 和 apply call bind》

apply call bind 的作用

1,JavaScript 中函数是一个对象,所以函数能够有要领
2,apply call bind 都是函数的要领,用来给函数指定 this

apply

1,apply 接收两个参数
2,第一个参数为函数里的 this
3,第二个参数为要传给函数的参数列表,(这个参数列表能够当作是个数组来明白,实际上不是数组
4,apply 会把这个参数列表拆成一个个的参数传给函数

比方

console.log.apply(console, arguments)

这行代码把 log 函数的 this 指定为 cosnole.log

var arguments = [1, 2, 3]
console.log.apply(console, arguments)
// 相当于 
console.log(1, 2, 3)

《JavaScript 的 this 和 apply call bind》

call

call 和 apply 相似,区别是 call 只能把参数一个个传入

比方

console.log.call(console, 1, 2, 3)
// 相当于 
console.log(1, 2, 3)

《JavaScript 的 this 和 apply call bind》

bind

1,bind 只能返回一个函数让你挪用
2,bind 的第一个参数为函数里的 this
3,bind 还能够有分外的参数

比方

var log = console.log.bind(console, '这里是分外参数')
log('hello')

《JavaScript 的 this 和 apply call bind》

    原文作者:TaoWu
    原文地址: https://segmentfault.com/a/1190000018745281
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞