js中this关键字的指向
来源:互联网 发布:智能语音拨号软件 编辑:程序博客网 时间:2024/04/28 20:00
在函数执行时,this总是指向调用该函数的对象,有调用对象则指向该对象,无调用对象则指向全局对象window。
1.元素button点击事件函数
btn.onclick = function (event) { console.log(event); // event指向该点击事件对象 console.log(this); // this指向事件的目标元素,可以访问元素的属性 console.log(this.id);}
2.有对象就指向调用对象
var myObj1 = {value: 1}; myObj1.getValue = function () { console.log(this.value); // 输出1 console.log(this); // 输出 {value: 1, getValue: function}};myObj1.getValue();
3.没有对象就指向全局对象window
var myObj2 = {value: 1};myObj2.getValue = function () {var foo = function () { console.log(this.value); // 输出 undefined console.log(this); // 输出 window对象 // foo虽然定义在getValue函数内,但并没有绑定在任何对象上,故在调用时,指向全局对象window} foo(); return this.value;}console.log(myObj2.getValue()); // 输出1
4、用new构造函数,指向新对象
var Person = function () { this.age = 10;};var person1 = new Person();console.log(person1.age);
5.通过apply 或 call 或 bind 来改变this的指向
var myObj3 = {value: 100};var foo = function () { console.log(this);};foo();foo.apply(myObj3);foo.call(myObj3);var newFoo = foo.bind(myObj3);newFoo();
转载自:http://blog.csdn.net/junbo_song/article/details/52261247
阅读全文
0 0
- js中this关键字的指向问题
- js中this关键字的指向
- JS:this关键字的指向
- js中this的指向
- js中this的指向
- js中this的指向
- js中this的指向
- js中 this 的指向
- js中this的指向
- js中this的指向
- JS中this的指向
- Js中this的指向
- JS中this指向
- JS 改变函数中 this 的指向
- [JS]事件函数中this的指向
- 了解学习JS中this的指向
- 彻底理解js中this的指向
- 彻底理解js中this的指向
- JSON与XML面试题
- ubuntu
- Redis学习第五节
- 自动内存管理机制_运行时数据区域
- JAVA FILE.separator
- js中this关键字的指向
- TCP小型服务器(poll)
- jdbc; java 连接数据库
- 泛型的总结
- Kotlin基本语法(一)
- 【算法概论】习题8.12证明题
- 单片机时钟程序(8)lcd1602.c
- Spring Boot入门——集成Mybatis
- java集合框架笔记(1)