温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js私有方法、公有方法、特权方法总结

发布时间:2020-06-15 00:58:11 来源:网络 阅读:824 作者:pmlinjian 栏目:开发技术

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

公有方法: 

  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


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI