日期:2014-05-16  浏览次数:20312 次

javascript面向对象2

javascript中面向对象中分为公有 , 私有 , 特权 , 静态成员。(摘自视频,我是javascript菜鸟)

?

说明如下:

function MyClass(name , age) {

???? this.name = name? ;

???? this.age = age;

???? var tmpStr = 'Hello , world!';

???? this.printAll = function() {

?????????? alert(this.name + ":" + this.age);

???? };

???? this.accessInner = function() {

?????????? alert('access from public : ' + tmpStr);

???? };

}

MyClass.prototype.newAttr = 'newAttr';

MyClass.prototype.appendFunction() {

?????? alert('can append function out side the constructor , ' + this.newAttr);

?????? //执行下面这句会是undefined

?????? alert(tmpStr);

};

name , age , printAll 都是公有成员 , newAttr ,appendFunction都是特权成员。

tmpStr是私有成员

公有成员可以访问私有成员,但是有顺序,在私有成员定义之后才能访问。

特权成员不可以访问私有成员。

特权成员可以访问公有成员。

公有成员可以访问特权成员。

特权成员与公有成员之间访问没有先后顺序。

?

下面说静态成员

?????????? function myObject(){
?? ??? ??? ??? ?this.c = 'c';
?? ??? ??? ?};
?? ??? ??? ?myObject.a = 'a';
?? ??? ??? ?myObject.fun = function() {
?? ??? ??? ??? ?alert('hello');
?? ??? ??? ?};
?? ??? ??? ?var o1 = new myObject();
?? ??? ??? ?var o2 = new myObject();
?? ??? ??? ?alert(o1.c);
?? ??? ??? ?alert(o2.c);
?? ??? ??? ?alert(o1.a);
?? ??? ??? ?alert(o2.a);
?? ??? ??? ?myObject.fun();
?? ??? ??? ?o1.fun();
?? ??? ??? ?o2.fun();

?上面定义的myObject中a和fun属于静态成员,这两个成员只能通过myObject.xxx的形式访问,

任何该myObject的实例都不能访问这两个成员。故称为静态成员。

此处静态与java中静态不同, java静态是既可以通过类名也可以通过对象访问的。

而javascript中的静态是只能通过类名不能通过对象访问的。