JavaScript 的 this 和 apply call bind

this 是谁
1,this 在函数运行时才能确定2,谁调用了函数谁就是 this3,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()

o1 调用了 hello 函数,所以 hello 函数中的 this 就是 o1(调用者是 o1o2 同理
什么是全局对象
1,浏览器的全局对象是 window2,node.js 中全局对象是 global
在浏览器中直接调用一个函数,那么 this 就是 window (调用者是 window
例如
var hello = function() {
console.log(‘this 是,’, this)
}
hello()

apply call bind 的作用
1,JavaScript 中函数是一个对象,所以函数可以有方法2,apply call bind 都是函数的方法,用来给函数指定 this
apply
1,apply 接受两个参数2,第一个参数为函数里的 this3,第二个参数为要传给函数的参数列表,(这个参数列表可以当做是个数组来理解,实际上不是数组4,apply 会把这个参数列表拆成一个个的参数传给函数
例如
console.log.apply(console, arguments)
这行代码把 log 函数的 this 指定为 cosnole
var arguments = [1, 2, 3]
console.log.apply(console, arguments)
// 相当于
console.log(1, 2, 3)

call
call 和 apply 类似,区别是 call 只能把参数一个个传入
例如
console.log.call(console, 1, 2, 3)
// 相当于
console.log(1, 2, 3)

bind
1,bind 只能返回一个函数让你调用2,bind 的第一个参数为函数里的 this3,bind 还可以有额外的参数
例如
var log = console.log.bind(console, ‘这里是额外参数’)
log(‘hello’)

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据