//---------公有方法------

公有方法:

  1.公有方法是可以在类的外部被调用的,

  2.但是它不可以访问类的私有属性。

  3.公有方法必须在类的内部或者外部通过类的prototype属性添加。


私有方法:私有方法本身是可以访问类内部的所有属性的,即私有属性和公有属性。但是私有方法是不可以在类的外部被调用。

//---------私有方法------

var pet=function(){  

var temp=""  //私有变量只有在函数或者对象作用域范围内能访问

function showpet(){

  alert("123")

}

showpet();//私有方法可以在函数作用域范围内使用。

}

showpet();//会出错

pet.showpet()//还是不能这样调用


var Penguin=new pet() //实例化一个pet对象

Penguin.showpet()//不好意思这样子还是不能让你调用。

//---------特权方法 -------

特权方法:特权方法是可以在类的外部被调用。(创建方法有如下两种)

方法1:通过构造函数使用this关键字定义一个特权方法;

function Person(name){

this.getName = function(){

return name;

};

this.setName = function (value) {

name = value;

};

}

var person = new Person("Nicholas");

alert(person.getName()); //"Nicholas"

person.setName("Greg");

alert(person.getName()); //"Greg"


方法2:通过在私有作用域中定义私有变量或者函数,在原型上定义特权方法。

(function(){


var name = "";

Person = function(value){

name = value;

};

Person.prototype.getName = function(){

return name;

};

Person.prototype.setName = function (value){

name = value;

};

})();


var person1 = new Person("Nicholas");

alert(person1.getName()); //"Nicholas"

person1.setName("Greg");

alert(person1.getName()); //"Greg"

var person2 = new Person("Michael");

alert(person1.getName()); //"Michael"

alert(person2.getName()); //"Michael"


资料参考:

http://www.jb51.net/article/30357.htm