javascipt 中this的学习小节

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <!--  js 中  this 的处理    -->

    <script>
        /**
        *   1   做为对象的方法调用
        *   2   做为普通的函数
        *   3   构造器调用
        *   4   Function.prototype.call 和 Function.prototype.apply.
        ***/
        /*
        *   做为对象的方法调用, 意味着this指向的对象中的属性和方法.
        **/

        var obj1 = {
            a: 1,
            getA: function () {
                console.log(this === obj1);
            }
        }

        obj1.getA();    //  true 


        /**
        *  做为普通的函数, 那么this的指向会是window.是一个全局的.
        *
        **/

        window.name = 'This is global obj';

        var obj2 = function () {
            return this.name;
        }

        console.log(obj2());     //  This is global obj

        var obj3 = {
            name: 'This is inside obj',
            get: function () {
                return this.name;
            }
        };

        // 注意这个地方的写法, 将一个函数做为普通变量,可变函数.总体指向了全局.
        var obj4 = obj3.get;
        console.log(obj4());     // This is global obj

        /**
        *    做为构造函数使用 , 若放回结果是一个非对象,那么this仍是指向当前的构造函数, 不然,以返回的对象为准.
        *    1  没有返回值的构造函数
        *    2  返回结果是一个对象的构造函数.
        **/
        
        var obj5 = function () {
            this.name = 'seven';
        }

        var obj6 = new obj5();
        console.log(obj6.name);     // seven
       
        /*
        *   明显的返回一个对象.
        */
        var obj7 = function () {
            this.name = 'six';
            return {
                name :'name'
            }
        }

        var obj8 = new obj7();
        console.log(obj8.name);    // name 

        /*
        * 明显的返回一个非对象.
        */
        var obj9 = function () {
            this.name = 'seve';
            return 'name';
        }


        var obj10 = new obj9();
        console.log(obj10.name);     // seve

        /**
         *  call,apply 的使用.
         */
        var obj11 = {
            name: 'zhang',
            getName: function () {
                return this.name;
            }
        }

        var obj12 = {
            name :'chao'
        }

        console.log(obj11.getName());              // this 做为对象的去使用
        console.log(obj11.getName.call(obj12));    //  做为call的参数.
        console.log(obj11.getName.apply(obj12));   // 做为apply的参数

    </script>

</body>
</html>
相关文章
相关标签/搜索