this是和执行上下文相关的对象,只有在运行的时候才能确定this的值;
this主要应用在:
- 构造函数中的this;
- 普通函数中的this;
- 对象函数中的this;
- call、apply、bind改变this
- 箭头函数中的this;
1. 构造函数中的this
function Person(name) {
this.name = name;
}
const p = new Person('xiaoming');
console.log(p.name);
2. 普通函数中的this
function getVal() {
console.log(this); //window
}
3. 对象函数
中的this
- 注意是对象函数中的this,不是对象中的this,对象中的this还属于上一级作用域中的this;
- 如果函数是声明式函数,则this为当前对象,如果函数是箭头函数,则this去上一级作用域链找;
- call并不能改变箭头函数中的this,因为箭头函数不会自己创建this;
注:作用域链寻找是指当前this所在的环境,和在哪里调用的无关,只和是谁调用的有关
。
例如obj里的this,因为obj是全局定义的,所以this是window,而不是因为在timer函数里调用了obj.clickFn()就改变this,this不会自己去传导。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>按钮</button>
<script>
let obj = {
name: 'xiaoming',
clickFn: () => {
console.log('this', this)
}
}
function timer() {
console.log(111, this)
obj.clickFn();
}
const btn = document.querySelector('button');
// const clickFn = () => {
// console.log('this', this)
// }
btn.addEventListener('click', timer.bind(obj))
</script>
</body>
</html>
const obj = {
name: 'xiaohong',
age: 18,
description: function() {
console.log(this); // obj
}
}
obj.description();
const obj2 = {
name: 'xiaohong',
age: 18,
description: () => {
console.log(this); //window
}
}
obj2.description();
4. call、apply、bind改变this
手写简单bind
if (!Function.prototype.mymyBind) {
Function.prototype.myBind = function (oThis) {
if (typeof this !== 'function') {
return;
}
// console.log('mybid', this);
let self = this;
let args = Array.prototype.slice.call(arguments, 1);
return function () {
return self.apply(oThis, args.concat(Array.prototype.slice.call(arguments))); //这里的arguments是执行绑定函数时的实参
};
};
}
const obj = {
name: 'xiaoming',
age: 18,
descrition: function(arg1, arg2) {
console.log(this);
console.log(arg1, arg2) // aa bb
}
}
const objBind = obj.descrition.myBind({name: 'aaaa'}, 'aa')
objBind('bb');
注意: 多次bind也只绑定了第一次的bind的对象,因为bind内部实现里返回了一个函数,如果这个函数没有执行,那么绑定的oThis永远是第一次bind的this。
再次手写bind
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// 注意: 箭头函数中没有this 和 arguments, 箭头函数的this 和 arguments要往上一次作用域链找
// if (!Function.prototype.myBind) {
// Function.prototype.myBind = (_this) => {
// const _args = Array.prototype.slice.call(arguments, 1);
// return () => {
// this.apply(
// _this,
// _args.concat(Array.prototype.slice.call(arguments))
// );
// };
// };
// }
if (!Function.prototype.myBind) {
Function.prototype.myBind = function(_this) {
const _args = Array.prototype.slice.call(arguments, 1);
const that = this;
return function() {
that.apply(_this, _args.concat(Array.prototype.slice.call(arguments)));
}
}
}
const obj = {
name: 'xiaoming',
age: 18,
descrition: function (arg1, arg2) {
console.log(this);
console.log(arg1, arg2); // aa bb
},
};
const objBind = obj.descrition.myBind({ name: 'aaaa' }, 'aa');
objBind('bb');
</script>
</body>
</html>
5. 箭头函数和普通函数的区别如下。
-
普通函数:根据调用我的人(谁调用我,我的this就指向谁)
-
箭头函数:MDN官方文档里面描述箭头函数this定义的时候,描述的是“箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this。",因此箭头函数里的this也不能够通过call方法来改变。
一. 箭头函数中的this
var name = 'hello'
const obj = {
name: 'obj',
a: () => {
console.log(this.name)
}
}
const obj1 = {
name: 'obj1'
}
obj.a.call(obj1) // hello
- 由于箭头函数中的this不能够被改变,故call方法无效;
- 箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this。
- 作用域分为块级作用域、函数作用域、全局作用域;没有对象作用域;
例如:
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
var id = 21;
foo.call({ id: 42 });
// id: 42
上面代码中,setTimeout的参数是一个箭头函数,这个箭头函数的定义生效是在foo函数生成时,而它的真正执行要等到 100 毫秒后。如果是普通函数,执行时this应该指向全局对象window,这时应该输出21。但是,箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this,所以输出的是42。
再例如:
function foo() {
(function () {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
})()
}
var id = 21;
foo.call({ id: 42 });
// id: undefined
上面代码中箭头函数的定义是在自执行函数里,所以此时的this是window,故而输出undefined。
箭头函数可以方便地让我们在 setTimeout ,setInterval中方便的使用this。
二. 普通函数中的this:
-
this总是代表它的直接调用者(js的this是执行上下文), 例如 obj.func ,那么func中的this就是obj
-
在默认情况(非严格模式下,未使用 ‘use strict’),没找到直接调用者,则this指的是 window (常见的window的属性和方法有: alert, location,document,parseInt,setTimeout,setInterval等)(约定俗成)
-
在严格模式下,没有直接调用者的函数中的this是 undefined
-
使用call,apply,bind(ES5新增)绑定的,this指的是 绑定的对象
var factory = function () {
this.a = 'a'
this.b = 'b'
this.c = {
a: 'a+',
b: function () {
return this.a
}
}
}
console.log(new factory().c.b()) //a+
var factory = function () {
this.a = 'a'
this.b = 'b'
this.c = {
a: 'a+',
b: () => {
return this.a
}
}
}
console.log(new factory().c.b()) //a