JS中this的指向

JS中this的指向,this是js中的一个关键字

1.this的指向有这四种情况

1. 在普通的函数中,this指向全局对象window
2.在构造函数中,this指向创造出来的实例
3.对象的方法里面调用,this指向调用者
4. 在函数中,严格模式下,this 是 undefined

// 普通方法中
function bar () {
	console.log(this) // this指向的是window
}
bar()
// 构造函数中
function Animal() {
	this.name = 'zzz',
	this.sayName = function () {
		console.log(this) // 指向的是a实例
	}
}
var a = new Animal()
a.sayName()
// 对象方法
var obj = {
	name: '张三',
	fullName: function () {
		console.log(this.name)
	}
}

obj.fullName() // 这的this指向 obj这个对象
// 函数严格模式下
<script type="text/javascript">
	'use strict'
	function a () {
		console.log(this)
	}
	a() // undefined
</script>

2.改变this的指向

  1. apply() apply(thisScope, [arg1, arg2, arg3…]) 只接收两个参数,
  2. call() call(thisScope, arg1, arg2, arg3…) 接收多个参数
  3. bind() bind(thisScope, arg1, arg2, arg3…) 接收多个参数,返回一个函数。在这个新函数中,this将永久地被绑定到了bind的第一个参数,无论这个函数是如何被调用的。
    第一个参数‘this’使用对象,后续参数作为参数传递给函数使用
// call 和 apply
function add (b, c) {
	return this.a + b + c
}
var o = {a: 1};
console.log(add.apply(o, [4, 5]))  // 1+4+5 = 10
console.log(add.call(o, 4, 7))     // 1+4+7 = 12
// g使用bind绑定后,再重新对新函数g绑定,bind只会生效第一次绑定的
function add (b, c) {
	return this.a + b + c
}
var g = add.bind({a: 1}, 1, 2)   // 4
console.log(g())

var c = g.bind({a: 10}, 1, 11)  // 4
console.log(c())
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值