在javascript中,公有方法是指能被外部访问并调用的方法;而私有方法是指在对象的构造函数里声明,外部不可见且不可访问的方法。
本教程操作环境:windows7系统、javascript1.8.5版、dell g3电脑。
一:公有方法
公有方法就是能被外部访问并调用的方法
// 对象中var test1 = { name:'大白', getname:function(){ console.log(this.name); }}//调用test1.getname();//大白// 构造函数中function test2(name,age){ this.name = name; this.age = age; //公有方法 this.getname = function(){ console.log(this.name); }}// 在原型中test2.prototype.getage = function(){ console.log(this.age);}//调用var test3 = new test2('小白',12);test3.getname();//小白test3.getage();//12
二:私有方法和公有方法
特权方法是指有权访问内部私有属性和私有方法的公有方法(能够访问私有方法,私有属性的方法叫特权方法,也是公有方法的一种)
私有方法是指在对象的构造函数里声明,外部不可见且不可访问的方法。
使用不同方式定义私有方法和特权方法的形式不同
在对象中我们通过object对象表达式来创建一个对象并添加一些属性和方法,然后直接采用静态的方式调用。如rest.getname();
立即执行函数对象的私有数据放置在一个匿名函数立即执行表达式(iife)中,这意味着这个函数只存在于被调用的瞬间,一旦执行后就立即被销毁了
var yourobject = (function() { // 私有属性和方法 return { // 公有方法和属性 }}) ();
这里和前面的定义rest一样啊,可以通过yourobject直接的访问。这样的模块化的访问还是比较的厉害的。
var test4 = (function(){ //私有属性 var total = 10; // 私有方法 var buy = function(){ total--; } var get = function(){ return total; } return { name:'小白白', gettotal:get,//使用了闭包的方式来简介使用内部私有变量 buyfood:buy }})();test4.buyfood();console.log(test4.name);//小白白console.log(test4.gettotal());//9
使用了闭包的方式来间接使用内部私有变量
构造函数中定义私有属性和方法很方便,我们不需要使用闭包,可以在调用的时候初始化数据
// 构造函数中function test5(name) { // 私有属性 var total = 10; // 公有属性 this.name = name; // 私有方法 function _buyfood() { total--; } // 特权方法,才能访问私有的属性和私有的方法 this.buy = function() { _buyfood(); } this.gettotal = function() { return total; }}// 公有方法, 注意这里不能访问私有成员_totaltest5.prototype.getname = function() { //console.log(_total); // uncaught referenceerror: _total is not defined return this.name;}var test6 = new test5('大小白');console.log(test6.getname()); // '大小白'test6.buy();console.log(test6.gettotal()); // 9
结合使用
使用构造函数方式可以传入一些初始化的数据,但在公有方法中无法访问到私有成员属性,如果有很多公有方法需要访问私有数据,我们全部用特权方法来写,最后会给每个实例带去很多没有必要的方法。
var test7 = (function(){ // 私有属性 var total = 10; // 私有方法 function buyfood(){ total--; } // 构造函数 function test7(name){ this.name = name; this.gettotal = function(){ return total; } } // 公有方法 这里不是test7内部的私有 test7.prototype.buy = function(){ console.log(total); buyfood(); } test7.prototype.getname = function(){ return this.name; } return test7;})();var test0 = new test7('大大白');console.log(test0.getname());//大大白test0.buy();//10console.log(test0.gettotal());//9
【相关推荐:javascript学习教程】
以上就是javascript中公有方法和私有方法是什么的详细内容。