7,把对象当成参数,来组织和改善函数
在现代Web开发中,对象最普遍的一个用途是把它们当成函数的参数。要记住函数参数的这个规则总是很困难的;但是,使用一个对象是十分有好处的,因为我们不必再担心参数的规则了。而且,它更有组织性,可以让用户更好的理解我们要做什么。这个方法可以让你把对象当成参数,来组织和改善函数。例如:
- function insertData(name,lastName,phone,address){
- code here;
- }
重构以后的代码是这样的:
广州网站建设,网站建设,广州网页设计,广州网站设计
- function insertData(parameters){
- var name = parameters.name;
- var lastName = parameters.lastName;
- var phone = parameters.phone;
- var address = parameters.address;
- }
当你要使用默认值的时候,它也是十分有用的。例如:
- function insertData(parameters){
- var name = parameters.name;
- var lastName = parameters.lastName;
- var phone = parameters.phone;
- var address = parameters.address;
- var status = parameters.status || 'single' //If status is not defined as a property //in the object the variable status take single as value
- }
现在,要使用这个函数十分的简单;我们可以用两种方式来发送数据:
- //Example 1
- insertData({name:’Mike’, lastName:’Rogers’, phone:’555-555-5555’,address:’the address’, status:’married’});
- //Example 2
- var myData = { name:’Mike’,
- lastName:’Rogers’,
- phone:’555-555-5555’,
- address:’the address’,
- status:’married’
- };
- insertData(myData);
8,函数就是数据
函数就是像strings或numbers那样的数据,我们可以把它们当成函数参数来传递它们,这可以创建十分令人惊讶而又“威风凛凛”的Web应用程序。这个方法是非常有用的,几乎所有的主流框架都使用了这个方法。例如:
广州网站建设,网站建设,广州网页设计,广州网站设计
- function byId(element, event, f){
- Document.getElementById(element).['on'+event] = f; //f is the function that we pass as parameter
- }
- byId('myBtn','click',function(){alert('Hello World')});
- Another example of functions as data:
- //Example 1
- function msg(m){
- Alert(m);
- }
- //Example 2
- var msg = function(m){ alert(m);}
这些函数几乎是完全相同的。唯一的区别是使用它们的方式。例如:第一个函数,在你声明它以前,你就可以使用它了;但是第二个函数只有声明以后才能使用:
- //Example 1
- msg('Hello world'); //This will work
- function msg(m){
- alert(m);
- }
- //Example 2
- msg('Hello world'); //Does not work because JavaScript cannot find the function msg because is used before is been declared.
- var msg = function(m){ alert(m)}
9,扩展本地对象
虽然一些JavaScript的领袖不推荐这个技术,但是它已经被一些框架使用了。它可以让你针对JavaScript API来创建一些辅助性的方法。
- //We create the method prototype for our arrays
- //It only sums numeric elements
- Array.prototype.sum = function(){
- var len = this.length;
- total = 0;
- for(var i=0;i<len ;i++){
- if(typeof this[i]!= 'number') continue;
- total += this[i];
- }
- return total;
- }
- var myArray = [1,2,3,'hola'];
- myArray.sum();
- Array.prototype.max = function(){
- return Math.max.apply('',this);
- }
10,Boolean
注意它们之间的区别,因为这会节省你调试脚本的时间。
- '' == '0' // false
- 0 == '' // true
- 0 == '0' // true
- false == 'false' // false
- false == '0' // true
- false == undefined // false
- false == null // false
- null == undefined // true
- true == 1 // true
- '' == null // false
- false == '' // true
如果你在其他地方看过这些脚本,那么这些技巧可以帮助你融会贯通。这些技巧甚至还不及JavaScript所有功能的冰山一角,但是这是一个开始!请不要客气,留下你的评论,问题,额外的技巧或疑虑吧,但是请记住,这是一篇针对初学者的文章!!我希望能收到一些开发者同行的来信!Enjoy!