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是已经有值的)

原文地址:https://www.cnblogs.com/dongzhiquan/p/1994687.html