-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[js] 第33天 说说你对this的理解 #120
Comments
js 中有两个重要概念:作用域和原型链 我个人感觉 |
this在不同场景下指向也不同,比如有可能指向new出来的对象,可能指向全局对象,通过apply/call/bind还可以指向传入的第一个参数,等等。。。 |
this指的是当前运行环境的上下文。当然这个this是会发生改变的 如 bind call apply |
基本上可以归为四类, |
不严谨说法,谁调用这个函数,this就指向谁。 |
JavaScript 中的 下面是最常见的例子: const obj = {
sayThis: function() {
console.log(this);
}
};
obj.sayThis(); // obj
const globalSay = obj.sayThis;
globalSay(); // window 浏览器中的 global 对象
这个“谁”我们可以通过 JavaScript 给我们提供了 把上面的例子改为箭头函数,结果完全不同。 const obj = {
sayThis: () => {
console.log(this);
}
};
obj.sayThis(); // window 因为 JavaScript 没有块作用域,所以在定义 sayThis 的时候,里面的 this 就绑到 window 上去了
const globalSay = obj.sayThis;
globalSay(); // window 浏览器中的 global 对象 |
https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/objects-classes/ch2.md |
|
箭头函数 |
一般情况函数中的
箭头函数箭头函数中的 |
如果函数是独立调用的话this就指向的是全局对象,如果是对象调用那么就指向的是这个对象,并且通过call/apply可以改变this指向,对比箭头函数中的this指向的是父级作用于中的this,并且通过call/apply无法改变this指向。 |
基本上可以归为四类, |
|
全局this指向window |
`## 什么是this this的指向首先判断函数类型
|
谁调用指向谁 |
this是指当前运行环境的上下文,可以通过call、apply、bind来改变当前上下文。 箭头函数的this指向父级函数的this。 |
我的答案 this是一个关键字,被自动定义在所有函数的作用域中。 |
您好!我看到邮件后会立即联系您!
|
在JavaScript中,关键字
需要注意的是, 理解 |
第33天 说说你对this的理解
The text was updated successfully, but these errors were encountered: