JavaScript Effective
习惯了面向对象和面向过程,最近发现JavaScript 是函数式的编程 之前写的都是看成函数 ,调用 ,调用,数据和操作总是没有分离。JavaScript的面向对象还没有习惯,记录下 原型,柯里化(Scala竟然也是函数式编程),以及一些高大的名词,例如高阶函数
函数调用
直接调用()
function hello(username){
return "hello"+username;
}
方法调用
var obj={
hello:function(){
return "hello"+this.username;
// 注意this的引用
},
username:"Who"
};
obj.hello();
function hello(){
return "hello"+this.username;
}
var obj1={
hello:hello,
username:"GGG"
}
obj1.hello(); // "hello, GG"
var obj2={
hello:hello,
username:"DDD"
}
obj2.hello();// hello,DDD
hello()// "hello,undefined" this 指向全局变量,然全局没有username属性
// 如果hello()中 "user strict" 则会出现error
构造函数使用
function Person(name,id){
this.name=name;
this.id=id;
}
var p=new Person('RRR',22);
p.name;// 'RRR'
构造函数需要通过new运算符调用,产生一个新的对象作为接收者
高阶函数
可以查找 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
map, sort
将函数作为返回值或者参数 感觉强大
// 看到一个例子
function buildString(n,callback){
var result="";
for(var i=0;i<n;i++)
result+=callback(i);
return result;
}
var aIndex="a".charCodeAt(0);
var alphabet=buildString(26,function(i){return String.fromCharCode(aIndex+i);})
alphabet;
var number=buildString(16,function(i){return i;})
number;
柯里化
维基上的例子
var foo = function(a) {
return function(b) {
return a * a + b * b;
}
}
foo(3)(4)
(foo(3))(4) //将参数分开传递
call
apply
bind
- argument