JavaScript私有方法
some concepts: Java is from Sun Microsystem Inc., and JavaScript, called LiveScript before, is from Netscape; those two languages has little relationship with each other. Just their names confuse us.
个人一直以为javascript中没有私有成员(变量和方法)的说法,直到看完此文云雾骤散。
1.对象
Arrays, Functions, Objects都是对象。Objects是name-value pair的集合,name是string,value是strings、numbers、booleans、objects(arrays and functions etc.)。objects使用哈希表实现其告诉取值的特性。
1.对象可由.ctor来生成,跟其他语言中的构造函数差不多,也是做初始化工作。
2.javascript中没有class的概念,可以用定义function的方式来模拟一个类。如,function Person(){...}。
3.也可以使用JSON定义:
<script type="text/javascript"> var Employee ={ "empID":"", "empFirstName":"", "empLastName":"", "setValues":function(id,fname,lname){ this.empID = id; this.empFirstName = fname; this.empLastName = lname; }, "getValues":function(){ alert(this.empID + " " + this.empFirstName + " " + this.empLastName); } } function main(){ Employee.setValues("1142″,"Yogesh","Jaiswal"); Employee.getValues(); } </script> HTML Code : <div> <asp:Button ID="btnCallmain" runat="server" Text="CallMain" OnClientClick="javascript:main();"/> </div>
4.继承机制是指,objects inherit from objects, not classes,因为没有类的概念。
2.Public
object的所有成员默认都是public的,任何function都可以访问、修改、删除已存在的成员,或增加新的成员。将成员加到Object中有两种主要的方法:
1) 使用构造函数.ctor,如:
function Person(name){this.Name=name;};
此方法通常初始化public instance variables;var paul=new Person("paul cheung");此时,paul.Name就是"paul cheung"。
2)使用原类型prototype(从原文得知,某object的prototype是此object的构造函数的一个成员),如:
Person.prototype.Greet = function(target){return "hi, " + target;}
此方法一般用于添加public methods,比如Shakehand方法没有在Person object中找到,此时就会去Person的prototype成员里找,这个很重要,直接上原文:When a member is sought and it isn't found in the object itself, then it is taken from the object's constructor's prototype member. The prototype mechanism is used for inheritance. It also conserves memory. To add a method to all objects made by a constructor, add a function to the constructor's prototype;
这就是prototype继承机制;paul.Great("chris paul")会返回"hi, chris paul".
3.Private
构造函数里的成员(变量、参数)都是私有的(这个比较费解,刚demo出来的貌似有出入,理解错了难道?我用IE10);构造器里的函数都是private的:
>> function Container(param) { this.member = param; var secret = 3; var that = this; #构造函数创建三个私有变量,添加到object上,不能被外部和public方法访问;只有私有方法可以访问(为啥Greet方法可以访问member?)
} Container.prototype.Greet = function(){console.log(this.member);} #Greet() is public? if so why c.Greet() can get this.member?f**k
c = new Container("paul's container") c.member #can not get this member; c.Greet(); paul's container #c.Greet();
PS:可以对变量进行数值检测,进而赋值或做其他操作;
4.Privileged
此种方法可以访问private变量或private方法,外部或public方法可以访问privileged方法,可以删除或替换privileged方法,但不能更改。
5.Closures(闭包?)
理解起来还是迷迷糊糊,两个链接以备后用: Private Members in JavaScript,by Douglas Crockford; and Natural JavaScript private methods, by Andrea Giammarchi.
posted on 2013-07-24 16:27 paul_cheung 阅读(334) 评论(0) 编辑 收藏 举报