使用 this 指针和 prototype 实现 js 的 OO 时的一个区别 利用 this 实现的公共方法中可以访问类的私有成员(用 var 声明的变量),私有方法(用 function 直接定义的方法); 利用原型扩展实现的方法中,无法调用私有成员和变量。 例子如下所示(把其中注释掉的两行恢复就可以看到区别): function T(name) { this .Name = name; var x = 5 ; function privateFunc() { alert(' in private method: do sometheing'); } this .PublicFunc = function () { // 可以调用私有方法,访问私有成员变量。 privateFunc(); alert('x = ' + x); alert(' in public method: do something else .'); } } // var t = new T('t1'); // t.PublicFunc(); T.prototype.PublicFunc2 = function () { alert(' in public method 2 .'); // 下面两行都会出错。在利用 prototype 扩展的方法里无法调用对象的私有方法,也访问不到通过 var 定义的私有成员。 // alert(x); // privateFunc(); } var t2 = new T('t2'); t2.PublicFunc(); t2.PublicFunc2(); posted on 2005-03-02 09:54 木野狐(Neil Chen) 阅读(812) 评论(3) 编辑 收藏 所属分类: 网页技术 发表评论 回复 引用 查看 2005-11-03 17:37 | 49220251 [未注册用户] 写的好!少而精,这才是程序精神 回复 引用 查看 2006-02-10 16:55 | icyker [未注册用户] http://www.crockford.com/javascript/private.html <script language="JavaScript"> <!-- function test1(){ this.a = "a"; function b(){ return this.a; } function c(){ return "aaa"; } this.d= function(){ return this.a; } this.e = function(){ return c(); } this.f = function(){ return b(); } } var d = new test1(); alert(d.d()); alert(d.e()); alert(d.f()); //--> </script> 大哥能解释一下为什么d.f()会返回undefined? 有人说在b()里this改变了,但我用constructor返回的却是test1,我实在搞不清楚怎么回事了,还望指点 回复 引用 查看 2007-01-26 10:20 | lindeqiang(at)hotmail.com [未注册用户] 回答楼上: 因为function b(){ return this.a; } 是一个私有方法,不能访问类对象this.a; 但可以访问: 用var 定义的成员 如: function test1(){ var aaa="ldq..."; function b(){ return aaa; } this.otherFunc=function(){ alert(b()); } 这样就可以!