this
来源:互联网 发布:云计算工程师就业 编辑:程序博客网 时间:2024/05/22 03:11
this是Javascript语言的一个关键字。
this代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。比如,
function test(){ this.name = 'test';}
this的值会随着函数使用场合的不同而发生变化。但是不变的是,this指的是,调用函数的那个对象。
关于this指向问题,与函数调用息息相关,其可大致分为四类情况:
- 方法调用; 即作为某对象的方法调用。
- 函数调用;即作为普通函数调用。
- 构造器函数调用;即以new方式调用。
- call与apply调用;即以Function.prototype.call或Function.prototype.apply调用。
#1 方法调用
var obj = { name: 'xiaoming', getName: function() { console.log(this === obj); //输出true console.log(this.name); //输出xiaoming return this.name; }};obj.getName();
当函数作为对象的方法被调用时,this总是指向该对象。
#2 函数调用
var name: 'xiaoming';var getName = function() { console.log(this === window); //输出true console.log(this.name); //输出xiaoming return this.name; }};getName();
非严格模式下,当函数作为普通函数方式调用时,不论该函数调用时所处执行环境为何,this总是指向全局对象,JavaScript中即是window对象。
#3 构造器函数调用
var Person = function(name){ this.name = name || 'person';}var per = new Person('xiaoming');per.name; // xiaoming
当用new调用构造器函数时,总会返回一个对象,该对象可以看成是构造器函数一个实例,一般,此时构造器里的this就指向返回的这个对象。
#4 call和apply
var obj = { name: 'xiaoming', getName: function() { console.log(this === obj); console.log(this.name); return this.name; }};var obj2 = { name: 'xiaohong'};console.log(obj.getName()); // 输出xiaomingconsole.log(obj.getName.call(obj2)); // 输出xiaohongconsole.log(obj.getName.apply(obj2)); // 输出xiaohong
当以Function.prototype.call或Function.prototype.apply方式调用函数时,动态传入参数改变执行环境,此时this指向传入的对象。
0 0
- this
- this
- this
- this
- this
- this
- this
- this
- this
- this
- this
- $(this)
- this
- this
- this
- this
- $(this)
- this
- hdu 5790 prefix 主席树在线维护区间不同数的个数
- emacs for Mac命令
- Java实现简单的数据结构(一)
- smmu学习笔记之bus_set_iommu
- Python学习笔记13
- this
- JavaScript 随机数
- 【51nod1363】最小公倍数之和
- bzoj 3566: [SHOI2014]概率充电器 概率dp+树形dp
- neutron: linuxbridge 架构解析
- 微信公众号开发之VS远程调试
- Java--IO流(InputStream,OutputStream,拷贝)
- OC中创建线程的方法是什么?如果在主线程中执行,方法是什么?如果想延时执行代码,方法是什么?
- linux驱动基础开发0——linux 设备驱动概述