var大全

<script>
 var globalVar="globalVar";                       //(1)
 this.globalThisVar = "this.globalThisVar";  //(2)

 globalFunc.funcVar = "funcVar";     //(3)
 function globalFunc(){
  var localVar = "localVar";     //(4)
  this.localThisVar = "this.localThisVar"; //(5)

  function nestedFunc(){
   var nestedVar = "nestedVar";    //(6)
   this.nestedThisVar = "this.nestedThisVar";  //(7)
  }
  nestedFunc();
  this.publicMethod = function4obj;
 }
 function function4obj(){
  alert(this.localThisVar);
 }

 globalFunc.prototype.prototypeVar = "globalFunc.prototype.prototypeVar"; //(8)
 
 var obj = new globalFunc();
 obj.objVar = "obj.objVar";      //(9)
 obj.publicMethod();
 
 /*  9种变量:
  (1)、全局变量。(相对于window是私有变量)。可见范围:任意地方
  (2)、window的全局变量。可见范围:任意地方
  (3)、函数属性(类属性)。可见范围:函数内外均能使用,始终以globalFunc.funcVar访问,但以funcVar是不行的,否则就成了全局变量了
  (4)、私有变量(函数内的局部变量)。可见范围:仅被私有方法和特权方法访问,换句话说是仅在函数内可见。
  (5)、公有变量(函数内this引用的变量)(实例属性?)。可见范围:在函数内必须以this.localThisVar来访问,且在private method里访问不了。
           public method和previliged method里均需以this打头访问,可以obj.localThisVar访问。
  (6)、嵌套函数内的局部变量。可见范围:仅能在嵌套函数内使用。
  (7)、嵌套函数内this引用的变量。可见范围:window的属性,window内可见。
  (8)、原型对象的属性。可见范围:在全部地方都能以globalFunc.prototype.prototypeVar访问,obj以obj.prototypeVar访问。
  (9)、实例属性(对特定实例后来添加的,这在面向对象中似乎不常见)。可见范围:以obj.objVar访问。
 */
 /*1、注意到这里没有特权方法。特权方法的特权就是公有私有变量都能访问
   2、private variables and public properties are instantiated with each new object created.
   3、globalFunc.prototype.prototypeVar实例共享
   4、函数独享(函数内均能使用),实例不可访问,但可以通过obj.constructor.funcVar访问
   5、obj.objVar实例独享
 */
// alert(window.nestedThisVar);        //nestedThisVar被加到window的属性里了,nestedFunc的this是window
// alert(globalFunc.funcVar); alert(funcVar);       //see (3)
// alert(globalThisVar);            //window.alert();应该是window的public method吧?
// alert(window.globalThisVar);

//  globalFunc()内测试
//  alert(prototypeVar);             //错误
//  alert(funcVar);      //错误
//  alert(globalFunc.funcVar);   //正确
//  alert(globalFunc.prototype.prototypeVar); //正确

//   nestedFunc()内测试
//   alert(globalThisVar);  alert(globalVar);  alert(localVar); //意料之中
//   alert(globalFunc.funcVar);                     //see (3)这里居然也能用!
//   alert(localThisVar);          //nestedFunc不能使用外部的this.var
//   alert(globalFunc.prototype.prototypeVar);      //正确

// alert(obj.funcVar);         //see 4, undefined
// alert(obj.constructor.funcVar);                //see 4,funcVar
// alert(obj.prototypeVar);      //see 3
 
</script>
 

我花了几天收集了关于变量的定义以及它们的scope,做了一些试验,可能还有一些错误,希望大家交流交流。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值