javascript中的this
来源:互联网 发布:算法导论 代码实现 编辑:程序博客网 时间:2024/06/07 04:58
this
指运行时上下文执行环境,谁调用这个函数,this就是谁
1. 当在全局环境下,this指window
2. eval(…)中调用的函数,不管eval是被谁调用的,直接看函数里的this
3. 经对象调用obj.myMethod() ,或者 obj“myMethod”,this指向obj
4. 其他情况,this指向thisArg
Function.prototype.apply( thisArg, argArray )
Function.prototype.call( thisArg [ , arg1 [ , arg2, … ] ] )
Function.prototype.bind( thisArg [ , arg1 [ , arg2, … ] ] )
Array.prototype.every( callbackfn [ , thisArg ] )
Array.prototype.some( callbackfn [ , thisArg ] )
Array.prototype.forEach( callbackfn [ , thisArg ] )
Array.prototype.map( callbackfn [ , thisArg ] )
Array.prototype.filter( callbackfn [ , thisArg ] )
练习
<script type="text/javascript"> if (true) { // Line A } </script>
window Line A is evaluated in the initial global execution context.
<script type="text/javascript"> var obj = { someData: "a string" }; function myFun() { // Line B } obj.staticFunction = myFun; obj.staticFunction(); </script>
obj When calling a function on an object, ThisBinding is set to the object.
<script type="text/javascript"> var obj = { myMethod : function () { // Line C } }; var myFun = obj.myMethod; myFun(); </script>
window In this example, the JavaScript interpreter enters function code, but because myFun/obj.myMethod is not called on an object, ThisBinding is set to window. This is different from Python, in which accessing a method (obj.myMethod) creates a bound method object.
<script type="text/javascript"> function myFun() { // Line D } var obj = { myMethod : function () { eval("myFun()"); } }; obj.myMethod(); </script>
window This one was tricky. When evaluating the eval code, this is obj. However, in the eval code, myFun is not called on an object, so ThisBinding is set to window for the call.
<script type="text/javascript"> function myFun() { // Line E } var obj = { someData: "a string" }; myFun.call(obj); </script>
obj The line myFun.call(obj); is invoking the special built-in function Function.prototype.call(), which accepts thisArg as the first argument.
参考:http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work
0 0
- 【javascript】javascript中的this
- JavaScript中的this指针
- javascript 中的"this"
- javascript中的this!
- Javascript中的this讲解
- Javascript中的this关键字
- javascript中的this
- JavaScript中的this关键字
- JavaScript中的this详解
- JavaScript中的this指针
- javascript中的this
- JavaScript 中的this 关键字
- 有关javascript中的this
- javascript中的this
- JavaScript 中的 this
- Javascript中的this
- javascript中的this
- JavaScript中的this用法
- IE中iframe的跨域问题
- python中if __name__ == '__main__'
- JDBC回顾二PreparedStatement与Statement
- RabbitMQ简单收发,HelloWorld
- VMware中CentOS-7无法访问网络和putty无法连接问题
- javascript中的this
- 使用单选框,复选框,让用户选择
- java源码解读之String
- PAT B1008. 数组元素循环右移问题 (20)
- POJ 3276 Face The Right Way (反转)
- bzoj 1972: [Sdoi2010]猪国杀 (大模拟)
- Java多线程(0)——线程与进程的区别
- 【JZOJ 4984】太空飞船
- Android活动的四种启动模式