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