标签:概念 expected 简单 throw class类 等等 ted 语言 实现
前言:
上一篇介绍了 函数回调,高阶函数以及函数柯里化等高级函数应用,同时,因为正在学习JavaScript·函数式编程,想整理一下函数式编程中,对于我们日常比较有用的部分。
为什么函数式编程很重要?
1 function fail(err){ 2 throw new Error(err); 3 } 4 function warn(err){ 5 console.log("Warning thing:%s",err); 6 }
1 var Person=function(){ 2 // 定义私有变量 3 var school="SCUT"; 4 // 定义公共接口方法 5 return { 6 name:‘‘, 7 setName:function(name){ 8 this.name=name; 9 }, 10 getName:function(){ 11 return this.name; 12 }, 13 getSchool:function(){ 14 return school; 15 } 16 } 17 } 18 var person1=new Person() 19 // => undefined 20 person1.school 21 // => undefined 22 person1.getSchool() 23 // => "SCUT"
1 var Person=function(){ 2 this.name=‘‘; 3 this.school="SCUT"; 4 this.setName=function(name){ 5 this.name=name; 6 }; 7 this.getName=function(){ 8 return this.name; 9 }; 10 this.getSchool=function(){ 11 return this.school; 12 } 13 } 14 var person1=new Person() 15 person1.getSchool() 16 //=> "SCUT" 17 person1.school 18 //=> "SCUT" 19 person1.school=‘JYYz‘ 20 person1.getSchool() 21 //=> "JYYz"
1 person1.school 2 // => undefined
1 nativeNth(‘hello‘,2) 2 //=> "l" 3 nativeNth({},2) 4 //=> undefined 5 可以看到,当传入不正确的值时候,会发生错误;对之进行修改如下: 6 function nativeNth(a,index){ 7 if(!Number.isInteger(index)) fail("Expected a number as the index"); 8 if(!Array.isArray(a) && typeof a !==‘string‘) 9 fail("Non supported on non-indexed type"); 10 if((index<0)||(index>a.length-1)) 11 fail("index value is out of bounds"); 12 return a[index]; 13 }
标签:概念 expected 简单 throw class类 等等 ted 语言 实现
原文地址:http://www.cnblogs.com/kasmine/p/6349795.html