this指向的4种场景
来源:互联网 发布:北京知金教育 编辑:程序博客网 时间:2024/06/15 23:39
之前一直对js里的this的指向搞不明白,特地花了时间去学习了this到底指向什么,于是把this出现的场景做了总结,this指向主要分为四类:
1.有对象就指向调用对象:
var myObject = {value: 100};myObject.getValue = function () { console.log(this.value); // 输出 100 // 输出 { value: 100, getValue: [Function] }, // 其实就是 myObject 对象本身 console.log(this); return this.value;};console.log(myObject.getValue()); // => 100
harry有话说:在对象myObject上绑定方法,在方法中this就指向对象myObject。
2.没调用对象就指向全局对象:
var myObject = {value: 100};myObject.getValue = function () { var foo = function () { console.log(this.value) // => undefined console.log(this);// 输出全局对象 global }; foo(); return this.value;};console.log(myObject.getValue()); // => 100
harry有话说:这里嵌套函数foo并没有直接绑定的对象,所以函数内的this指向全局对象global。
3.用new构造就指向新对象:
var SomeClass = function(){ this.value = 100;}var myCreate = new SomeClass();console.log(myCreate.value); // 输出100
harry还有话要说:myCreate就是调用对象
4.通过apply或call或bind来改变this的所指:
var myObject = {value: 100};var foo = function(){ console.log(this);};foo(); // 全局变量 globalfoo.apply(myObject); // { value: 100 }foo.call(myObject); // { value: 100 }var newFoo = foo.bind(myObject);newFoo(); // { value: 100 }
harry总结一下好了:apply(),call(),bind()方法,将this指向函数的第一个参数对象。
0 0
- this指向的4种场景
- JavaScript的三种this指向问题
- this指向 最简单的两种!
- 简单的几种this指向
- JS this的指向
- JavaScript-this的指向
- js的this指向
- this对象的指向
- this的指向
- this的指向
- javascript的this指向
- this的指向问题
- javascript this的指向
- 关于this的指向
- this对象的指向
- 关于this的指向
- this的指向
- 修改this的指向
- win10下SOPC Builder 在generate时出现could not find /tmp, please create
- Anaconda之二——Anaconda更新失败解决办法
- [BZOJ4826][HNOI2017]影魔-单调栈-线段树
- File的运用1
- ArcGIS Web客户端开发(附录)关于Dojo的基本知识
- this指向的4种场景
- Active MQ 管理界面介绍
- 为什么要用 ORM? 和 JDBC 有何不一样?
- 用两个栈实现队列的功能和用两个队列实现栈的功能
- 记中国银联实习面试
- APARNET阿帕网
- sysctl命令
- jsp a标签如何传值,如何接受
- MAC上搭建Jenkins实现Android自动打包