论坛首页 Web前端技术论坛

javascript私有属性和信息隐藏

浏览 3540 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-11-26  
xml 代码
  1. 私有属性在构造函数中用var关键字定义,私有属性只能用特权函数公用访问,特权函数是在构造函数中用this关键字定义的函数。私有属性不能使用点记法来访问,只能用公用函数访问。   
  2. 如下是个例子   
  3.   
  4. function Vehicle() {   
  5.     var wheelCount = 4;   
  6.     var curbWeightInPounds = 4000;   
  7.   
  8.     this.getWheelCount = function() {   
  9.         return wheelCount;   
  10.     }   
  11.   
  12.     this.setWheelCount = function(count) {   
  13.         wheelCount = count;   
  14.     }   
  15.   
  16.     this.getCurbWeightInPounds = function() {   
  17.         return curbWeightInPounds;   
  18.     }   
  19.   
  20.     this.setCurbWeightInPounds = function(weight) {   
  21.         curbWeightInPounds = weight;   
  22.     }   
  23.   
  24.     this.refuel = function() {   
  25.         return "Refueling Vehicle with regular 87 octane gasoline";   
  26.     }   
  27.   
  28.     this.mainTasks = function() {   
  29.         return "Driving to work, school, and the grocery store";   
  30.     }   
  31. }   
  32.   
  33. function SportsCar() {   
  34.     this.refuel = function() {   
  35.         return "Refueling SportsCar with premium 94 octane gasoline";   
  36.     }   
  37.   
  38.     this.mainTasks = function() {   
  39.         return "Spirited driving, looking good, driving to the beach";   
  40.     }   
  41. }   
  42.   
  43. function CementTruck() {   
  44.     this.refuel = function() {   
  45.         return "Refueling CementTruck with diesel fuel";   
  46.     }   
  47.   
  48.     this.mainTasks = function() {   
  49.         return "Arrive at construction site, extend boom, deliver cement";   
  50.     }   
  51. }   
   发表时间:2007-11-26  
只讲其然,不讲其所以然,这种东西教育效果不好。
0 请登录后投票
   发表时间:2007-11-26  
类中不是用this变量声明的变量或者方法就可以称为私有的
0 请登录后投票
   发表时间:2007-11-26  
不对,这个和私有根本毫无关系,也根本不是什么类,只是js当中错巧支持函数链scope保留的一种机制。那私有属性可以通过圆形方法调用吗,也是类的方法,和this没吗区别
0 请登录后投票
   发表时间:2007-11-26  
这个里面的私有属性你不能在类外调用(使用圆点)这里的私有你可以借鉴下JAVA里的私有这个概念。

0 请登录后投票
   发表时间:2007-11-26  
我没那么说,我是说
function test(){
var a=123;
this.test1=function(){alert(a)};
}
test.prototype.test2=function(){alert(a)};
new test().test1();
new test().test2();

我是说既然是私有属性,那么test1 test2同为对象方法,是否都可以得到私有属性呢
0 请登录后投票
   发表时间:2007-11-26  
你的test2方法算是外部方法,不能访问到内部的私有属性
0 请登录后投票
   发表时间:2007-11-26  
那你这就牵强了,那比如
c=new test;
c.ddd=function(){alert(a)}

这个ddd到底是外部还是内部呢,又比如另外一个贴,inherit继承的方法,算外部还是内部呢
0 请登录后投票
   发表时间:2007-12-03  
看你这个例子还不如看这个 http://www.nirvanastudio.org/javascript/private-members-in-javascript.html  对Douglas Crockford的原文翻译 讲的非常清楚
0 请登录后投票
   发表时间:2007-12-03  
好像是Ajax基础教程里的代码 我说怎么这么眼熟`` 建议看这篇 http://www.nirvanastudio.org/javascript/private-members-in-javascript.html
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics