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>
相關文章
相關標籤/搜索