zoukankan      html  css  js  c++  java
  • JavaScript this 范围

    看例子

     <script type="text/javascript">
            var f = function () {
                name = 'hongda';
                age = 27;
                say = function () {
                    console.log(this.name + "||" + this.age);
                }
            }
            var method = function () {
                name = 'hongda2';
                age = 272;
                say = function () {
                    console.log(this.name + "||" + this.age);
                }
            }
        </script>

    由此可以看出这些name,age,say都是全局的,由window调用,say方法中的this就是window

     <script type="text/javascript">
            var f = function () {
                this.name = 'hongda';
                this.age = 27;
                this.say = function () {
                    console.log(this.name + "||" + this.age);
                }
            }
        </script>

    调用的对象是f的实例

     <script type="text/javascript">
           var f = function () {
               name = 'hongda';
               age = 27;
               say = function () {
                   console.log(this.name + "||" + this.age);
               }
           }
           var method = function () {
               var name = 'hongda2';
               var age = 272;
               var say = function () {
                   console.log(this.name + "||" + this.age);
               }
           }
        </script>

    发现method中的变量前有了 var,表示就在method这个范围内

    下面将证明method中的name,age,say是局部的

    发现method()实例化以后,全局的变量name,age,say没有发生变化

    下面个例子可以看出function即是类,又是方法

     <script type="text/javascript">
           var f = function () {
               this.name = 'hongda';
               this.age = 27;
               this.say = function () {
                   console.log(this.name + "||" + this.age);
               }
           }
        </script>

    var ff=new f(); f()是类

    window.f();  f()是方法

  • 相关阅读:
    表达式for loop
    用户输入
    字符编码
    变量字符编码
    Python安装
    Python 2 or 3?
    Python解释器
    2017中国大学生程序设计竞赛
    Educational Round 27
    Round #429 (Div.2)
  • 原文地址:https://www.cnblogs.com/hongdada/p/3110351.html
Copyright © 2011-2022 走看看