zoukankan      html  css  js  c++  java
  • JavaScript中的私有函数;Javascript构造函数的私有方法中访问其属性和公有方法

    私有函数

    构造函数中在定义一个function的时候,在内部只要不以this打头,就是一个俗称的函数体内的局部变量或局部function(js中function即对象)就是私有的.

    function Test(){
      this.Value = 111;

      var value = 222;
      this.Foo = function(){
      alert(this.Value);
      foo();
      }
      function foo(){
      alert(value);
      }
    }

    new Test().Foo();
    new Test().foo();

    公有私有的互访性

    下面抄袭,稍作修改(O(∩_∩)O~)


    function Class1(){
      this.i = 1;

      function nn()

      {

         this.i++;

      }

      this.aa = function(){
        nn;
      }
      this.bb = function(){
        this.aa();
      }
      this.cc = function(){
        this.bb();
      }
    }


    var o = new Class1();
    o.cc();
    document.write(o.i);//return 2

    从例子中可以看到:

    构造函数的公有方法访问其属性和其他公有方法是可以的,并且可以访问其他私有方法(不过免除了this.).


    function Class1(){
      this.i = 1;
      this.aa = function(){
        this.i ++;
      }
      var bb = function(){
        this.aa();
      }
      this.cc = function(){
        bb();
      }
    }
    var o = new Class1();
    o.cc();
    document.write(o.i);

    脚本出错!提示"对象不支持些属性或方法",错误在"this.aa();"一句,估计是bb被认为是一个新的构造函数,那"this.aa();"中的this已经不再是Class1,因而才提示没有aa方法,那在构造函数的私有方法中如何访问其属性和公有方法呢?下边是无忧脚本winter版主

    程序代码 程序代码
    function Class1(){
      var me=this;
      this.i = 1;
      this.aa = function(){
        this.i ++;
      }
      var bb = function(){
        me.aa();
      }
      this.cc = function(){
        bb();
      }
    }
    var o = new Class1();
    o.cc();
    document.write(o.i);

    私有函数想要访问公有方法必须先把this改名了,不然在非公有函数默认是可以是可以使构造函数的(this是已经有值的)

  • 相关阅读:
    通过命令行指定 Java 程序运行时使用的字符集
    Ubuntu Linux 开启 root 用户及其它登录问题的解决
    SLF4J 的几种实际应用模式 SLF4J+Log4J 与 SLF4J+LogBack
    Java 获取当前时间的年月日方法
    Eclipse 全屏插件
    Linux 下的纯 C 日志函数库: zlog
    如何使用 Log4j
    DAO 设计模式
    为什么要用 /dev/null 2>&1 这样的写法
    NSDate和NSString之间的转换
  • 原文地址:https://www.cnblogs.com/dongzhiquan/p/1994687.html
Copyright © 2011-2022 走看看