Js中this的指向


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

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

普通函数中

function con() {
    console.log(this) // 这里this指向的是全局window
}

con()

构造函数中

function Fantsy() {
	this.name = '范特西',
		this.fanName = function() {
			console.log(this) // 这里this指向的是a实例
		}
	}
var a = new Fantsy()

a.fanName()

对象方法

var obj = {
	name: '范特西',
	fullName: function () {
		console.log(this.name)
	}
}

obj.fullName() // 这里this指向obj这个对象

函数严格模式下

<script type="text/javascript">
	'use strict'
	function fan() {
		console.log(this)
	}

	fan() // 在这里this是 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())

文章作者: 烦恼范特西
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 烦恼范特西 !
评论
  目录