javascript中的this分析
2022/8/13 14:23:19
本文主要是介绍javascript中的this分析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
函数中的this
在标准函数中,this引用的是把函数当成方法调用的上下文对象,这时候通常称其为this值(在网页的全局上下文中调用函数时,this指向window)。
这个this值到底引用哪个对象,必须到函数被调用的时候才能确定,因此这个值在代码执行过程中可能会变。
箭头函数中的this
在箭头函数中,this引用的是定义箭头函数的上下文。也可以说this值取决于该函数外部非箭头函数的this值,且不能通过call(), apply(), bind()
方法来改变this值。
类中的this
类的声明基本上还是基于自定义类型声明的语法糖
class Person { constructor(name) { this.name = name; } getName() { return this.name } } typeof Person // function
等价于
function Person(name) { this.name = name } Person.prototype.getName = function() { return this.name }
class中的方法,除了静态方法,都是原型链上的,其中的name属性则是自由属性,不会出现在原型上,且只能在类的构造函数或方法中创建。
因为方法是原型上的,所以函数中的this指向的上下文就是实例对象。
const joey = new Person('joey') joey.getName(); //getName中的this,指向的是joey实例。
在react中
class ButtonDemo extends PureComponent { componentDidMount() { console.log(this); 实例 console.log(typeof this); object console.log(this instanceof ButtonDemo); true } hello() { console.log(this); // undefined } render() { return (<Button block={true} onClick={this.hello}>Click Me</Button>); } }
在react中,hello虽然是ButtonDemo实例的方法,但是调用的上下文是在Button的onClick方法中,这边的上下文指向已经不是ButtonDemo的实例了,最终点击后打印出来的this是undefined。
这篇关于javascript中的this分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?