JavaScript 学习

来源:互联网 发布:java分布式框架搭建 编辑:程序博客网 时间:2024/05/21 07:13

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) //将参数分开传递
  1. call

  2. apply

  3. bind

  4. argument
0 0