What's this?(js)
来源:互联网 发布:com域名攻击 编辑:程序博客网 时间:2024/06/06 04:12
What's this?
由于运行期绑定的特性,JavaScript 中的 this
含义非常多,它可以是全局对象、当前对象或者任意对象,这完全取决于函数的调用方式
随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象
作为函数调用
在函数被直接调用时this
绑定到全局对象。在浏览器中,window
就是该全局对象
console.log(this);function fn1(){console.log(this);}fn1();
内部函数
函数嵌套产生的内部函数的this
不是其父函数,仍然是全局变量
function fn0(){function fn(){console.log(this);}fn();}fn0();
setTimeout、setInterval
这两个方法执行的函数this也是全局对象
document.addEventListener('click', function(e){console.log(this);setTimeout(function(){console.log(this);}, 200);}, false);
作为构造函数调用
所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象
new 运算符接受一个函数 F 及其参数:new F(arguments...)。这一过程分为三步:
- 创建类的实例。这步是把一个空的对象的 proto 属性设置为 F.prototype 。
- 初始化实例。函数 F 被传入参数并调用,关键字 this 被设定为该实例。
- 返回实例。
看例子
function Person(name){this.name = name;}Person.prototype.printName = function(){console.log(this.name);};var p1 = new Person('Byron');var p2 = new Person('Casper');var p3 = new Person('Vincent');p1.printName();p2.printName();p3.printName();
作为对象方法调用
在 JavaScript 中,函数也是对象,因此函数可以作为一个对象的属性,此时该函数被称为该对象的方法,在使用这种调用方式时,this 被自然绑定到该对象
var obj1 = {name: 'Byron',fn : function(){console.log(this);}};obj1.fn();
小陷阱
var fn2 = obj1.fn;fn2();
DOM对象绑定事件
在事件处理程序中this
代表事件源DOM对象(低版本IE有bug,指向了window)
document.addEventListener('click', function(e){console.log(this);var _document = this;setTimeout(function(){console.log(this);console.log(_document);}, 200);}, false);
Function.prototype.bind
bind,返回一个新函数,并且使函数内部的this为传入的第一个参数
var fn3 = obj1.fn.bind(obj1);fn3();
使用call和apply设置this
call apply,调用一个函数,传入函数执行上下文及参数
fn.call(context, param1, param2...)fn.apply(context, paramArray)
语法很简单,第一个参数都是希望设置的this
对象,不同之处在于call
方法接收参数列表,而apply
接收参数数组
fn2.call(obj1);fn2.apply(obj1);
caller
在函数A
调用函数B
时,被调用函数B
会自动生成一个caller
属性,指向调用它的函数对象,如果函数当前未被调用,或并非被其他函数调用,则caller为null
function fn4(){console.log(fn4.caller);function fn(){console.log(fn.caller);}fn();}fn4();
0 0
- What's this?(js)
- what's this? 浅谈js中this的指向问题
- what's this?
- What's this: __attribute__((packed))
- what's this , it's a ruler
- What's Special About This Number?
- What’s all this fuss about Erlang
- What’s this agile testing all about?
- JS:what is this "Object.prototype" anyway...?
- What’s All This Sink and Source Current Stuff?
- what's
- cassandra (1) What's new
- 什么是Node?(What's node) (译)
- what's the cygwin and how cai i install this software
- What is this site?
- what is this?
- what is this api
- What is this?
- 微支付几个参数的获得
- 读书笔记3——《用户故事与敏捷方法》
- C# 策略模式
- 旋转体的体积和表面积
- 斐波那契Fibonacci数列第n个数的快速求法
- What's this?(js)
- 哈希表中线性探测再散列法及等概率条件下平均查找长度
- Android连接网络
- MATLAB关于贝叶斯分类器的程序设计问题
- 【CODE】DOM、Jquery、D3.js字体放大缩小效果
- 终于体会OpenCV的好处了
- 《ArcGIS Runtime SDK for Android开发笔记》——(3)、ArcGIS Runtime SDK概述
- 因无写入权限导致部署论坛后无法更新插件解决之道
- 移动APP的创意进度条设计