为了避免多个函数类型的全局变量,可以采用对象(object)或者函数原型(prototype),例如:
var checkObject = {
checkName : function(){},
checkMail : function(){},
checkPassword : function(){}
}
ex: -def: var obj = {a : function(x,y){return x+y;}}
-use: obj.a(1+2)
-result: 3
or :
var checkObject = function(){};
checkObject.prototype = {
checkName : function(){},
checkMail : function(){},
checkPassword : function(){}
}
!attention: we should use a new to apply this definition!
ex: -def: var obj = function(){}
obj.prototype = {a : function(x,y){return x+y;}}
-use: var b = new obj() ;
obj.a(1+2)
-result: 3
另外函数还有通过点方法添加属性的方法,这种方法和原型相比,每次创建新对象的时候点方法的属性都需要新的创建(赋值),而原型则不需要在创建新对象的时候进行具体的定义。比如:
var Book = function(id,name,type){
this.id = id;
this.name = name;
this.type = type;
}
or :
var Book = function(){}
Book.prototype = {
isJsBook : true
}
apply:
var b = new Book
result:
b.num = undefined;
b.name = undefined;
b.type = undefined;
b.isJsBook = true;
apply:
var b = new Book( 4, 'jQuery', '004')//创建对象时同时赋值
result:
b.num = 4;
b.name = 'jQuery';
b.type = '004';
b.isJsBook = true;