Javascript变量与方法

变量命名

  1. 变量必须以字母开头
  2. 变量也能以 $ 和 _ 符号开头(私有变量命名常用"_"开头)
  3. 变量名称对大小写敏感

变量声明&声明提前

通过var显式声明(var user)。若不声明,则为全局变量,即为window对象的属性,可通过window.user获取,其值为undefined,这个属性是可配置的,并可通过delete删除掉。也可在一条语句中声明多个变量

var a=1, b=2, c=3;
fakevar=4;

delete fakevar;//true
delete a; //false

JavaScript的函数作用域是指在函数内声明的所有变量在函数体内始终可见,这意味着变量在声明之前已经可用。这个特性被非正式的称为声明提前

 

var scope="global";
function f(){
    console.log(scope);  //undefined, not global
    var scope="local";
    console.log(scope);  //local
}

 

该代码等同于

var scope="global";
function f(){
    var scope;
    console.log(scope);  //undefined, not global
    scope="local";
    console.log(scope);  //local
}

变量可以重复声明

Javascript中,作用域是由函数划分的,而不是由块划分(如while, if, for)。不过代码总要有一个上下文对象,该对象通过this来体现,这个变量永远指向当前代码所处的对象中。

var val="test";              //window.val

if(true){
  var val="new test";       
}
document.write("val="+val);  //new test

function test(){
 var val="another test";
 document.write("val="+val);  //another test
}
test();
document.write("val="+val); // new test

使用匿名函数将全局变量转化为局部变量

太多的全局变量不是一个好习惯,因为它们可能会影响其他的类库,导致奇怪的现象出现

(function(){
    var key="test";
    var content=document.getElementById("content");
    content.innerHTML=content.innerHTML.replace(/test/g,"<span style='color:red;'>"+key+"</span>");
})(); 

 变量引用

引用是一个指向对象实际位置的指针,多个变量可以引用同一个对象,该对象的类型和值一改变,所有的这些变量也会相应的改变。须注意的是,引用指向的只能是具体的对象,而不是另一个引用,Javascript会沿着引用链一直上溯到原来的那个对象

var items=["one", "two", "three"];

var array=items;
items.push("four");

alert(array.length==4);

 函数

可实现函数重载,有能力判断参数数量以及参数类型

arguments判断参数数量

function toArray(){
  var arr=[];
  for(var i=0;i<arguments.length;i++){
     arr.push(arguments[i]);
    }
  return arr;
}
var myArr=toArray(1,2,3,4,5);

 typeof和constructor来判断参数类型

变量 typof 变量 变量.constructor
{key: "value"} object Object
["an","array"] object Array
function(){}  function Function
"This is a string" string String
158 number Number
true boolean Boolean
new User object User
null object  
undefined undefined  
if(typeof num=='string'){
  //...
}
if(num.constructor==String){
  //....   
}

var me=new User();
var you=new me.constructor();

 公有方法

 每个对象都有指向原型的基引用,给原型添加属性后,由该原型实例化的每个对象都会获得这些属性,也就使这些属性公有化了

function User(name,age){
 this.name=name;
 this.age=age;
}

User.prototype={
  //this指的是实例化后的对象
  getName: function(){
     return this.name;
  },
  getAge: function(){
     return this.age;
  }
};

 私有方法

不能被外部访问,能被私有属性访问,特权方法访问

function Classroom(students, teacher){
    //private method
    function argumentsCheck(){
        if(typeof students!='array'){
            throw "Invalid students, expected Array";
        }
    }
    argumentsCheck();
}

特权方法

能被外部访问,同时能访问私有属性,是动态生成的,而不是第一次编译就有了,比在对象上的prototype上绑定一个方法的开销更大,但功能更强大

function User(name, age){
    //private attribute
    var location='shanghai';
    this.name=name;
    //privileged method
    this.getAge=function(){
        return age;
    }
}

 静态方法

 静态方法不能在该对象的实例的上下文中访问

function User(name, age){
    this.name=name;
    this.age=age;
    
    this.getName=function(){return this.name;}
    this.getAge=function(){return this.age;}
}

User.cloneUser=function(user){
    return new User(
        user.getName(), user.getAge()
    );
}
var user=new User('bob', 14);
User.cloneUser(user);
user.cloneUser(user); // object user has no method cloneUser  

动态添加方法,可实现属性的getter/setter方法,注意使用闭包激发作用域

function User(properites){
   for(var i in properties){
        (function(which){
            var p=i;
            which["get"+p]=function(){
                return properties[p];
            }
            which["set"+p]=function(val){
                properties[p]=val;
            }
        })(this);   
    }   
}   

 总结:

  1. 变量命名可重复,使用时养成良好命名规范
  2. 变量作用域为函数,而非代码块;若不声明,则为全局变量,可使用匿名函数消除全局变量
  3. 方法可动态添加,有私有,公有,特权,静态之分
  4. 方法中可判断参数数目与参数类型,实现方法重载
  5. 方法使用时,注意上下文对象,也可使用apply, call指定上下文
posted @ 2014-05-25 16:04  Derek_Hu  阅读(532)  评论(0编辑  收藏  举报