JS类成员作用域研究
作者:大石头
来源:
发布时间:2006-12-25 10:03:17
共有40位读者阅读过此文
| 声明方式 |
访问方式 |
| 类内 |
类外 |
|
| 成员 |
this.成员 |
类名.prototype.成员 |
类名.成员 |
对象.成员 |
类名.prototype.成员 |
类名.成员 |
备注 |
| 基类 |
类内 |
var 成员 |
支持 |
undefined |
undefined |
undefined |
undefined |
undefined |
undefined |
仅测试属性 |
| this.成员 |
未定义 |
支持 |
undefined |
undefined |
支持 |
undefined |
undefined |
仅测试属性 |
| 类外 |
类名.prototype.成员 |
未定义 |
支持 |
支持 |
undefined |
支持 |
支持 |
undefined |
仅测试属性 |
| 类名.成员 |
未定义 |
undefined |
undefined |
支持 |
undefined |
undefined |
支持 |
仅测试属性 |
| 继承 |
类内 |
var 成员 |
未定义 |
undefined |
undefined |
undefined |
undefined |
undefined |
undefined |
仅测试属性 |
| this.成员 |
未定义 |
支持 |
支持 |
undefined |
支持 |
支持 |
undefined |
仅测试属性 |
| 类外 |
类名.prototype.成员 |
未定义 |
支持 |
支持 |
undefined |
支持 |
支持 |
undefined |
仅测试属性 |
| 类名.成员 |
未定义 |
undefined |
undefined |
undefined |
undefined |
undefined |
undefined |
仅测试属性 |
| 结论 |
| 1 |
var 成员 声明的是私有成员,别的方式无法访问,即使派生类也无法访问 |
| 2 |
this.成员 经过继承后,在派生类中用 类名.prototype.成员 也能访问了,基类则不行 这说明基类的普通成员经过继承后,成为派生类的原型成员 |
| 3 |
类名.成员 是以类为对象声明成员,别的方式无法访问,即使派生类也无法访问 |
| 4 |
对象.成员 形式访问原型成员时,会产生写复制, 该对象的该成员指向独享的新的副本 |
| 5 |
同时声明this.成员和原型成员会有冲突, 同等条件下(相同访问方式),优先使用this.成员 |
| 6 |
类名.成员和原型成员挺相似的,只是原型成员对外多了个只读且可被继承 |
| 7 |
原型方法和类.方法成员 中声明的this.成员将会自动成为类的原型成员,因为原型方法只能访问原型成员,类对象只能访问类对象。原型成员和类.成员可以在类定义后的任意地方定义,感觉就是想要什么成员就有什么成员,用了就有了 |
| 8 |
var cc=0; function clsPerson() { //var i = 666; this.i = 777; // 属性 类有固定的属性,类的实例却可以有不同的属性 this.Name = ""; // 名字 // 方法 this.Run = function() { document.write("<br>" + this.Name + " 跑呀……"); } clsPerson.w=678; clsPerson.prototype.j = 89; if (cc==0) { cc=1; //test2("内 var i", i); test2("内 this.i", this.i); test2("内 clsPerson.prototype.i", clsPerson.prototype.i); test2("内 clsPerson.i", clsPerson.i); } } function pp() { //test2("继承内 var i", i); test2("继承内 this.i", this.i); test2("继承内 pp.prototype.i", pp.prototype.i); test2("继承内 pp.i", pp.i); } //clsPerson.prototype.i = 888; //clsPerson.i = 999; var AA = new clsPerson(); test2("外 AA.i", AA.i); test2("外 clsPerson.prototype.i", clsPerson.prototype.i); test2("外 clsPerson.i", clsPerson.i); pp.prototype=AA; var BB = new pp(); //clsPerson.prototype.i = 888; //clsPerson.i = 999; test2("继承外 BB.i", BB.i); test2("继承外 pp.prototype.i", pp.prototype.i); test2("继承外 pp.i", pp.i); test2("外 clsPerson.prototype.k", clsPerson.prototype.k); clsPerson.prototype.Add = function() { this.k = 5+55000; } test2("外 clsPerson.prototype.k", clsPerson.prototype.k); clsPerson.prototype.Add(); test2("外 clsPerson.prototype.k", clsPerson.prototype.k); test2("外 clsPerson.m", clsPerson.m); clsPerson.inc = function() { this.m=1234; } clsPerson.inc(); test2("外 clsPerson.m", clsPerson.m); test2("外 clsPerson.w", clsPerson.w); test2("外 clsPerson.prototype.j", clsPerson.prototype.j);
|
|
|
|
|
|
|
|