Xiaopei's DokuWiki

These are the good times in your life,
so put on a smile and it'll be alright

User Tools

Site Tools


it:javascript:start

JavaScript

ES2016 与 CommonJS 的区别

模块(import/export vs require/exports)

// 在 ES5 中,如果要 require babel6 解析 ES2015 生成的模块,则需:
var foo = require('./foo.js');
 
if (foo.default) {
    foo = foo.default;
}

ES7

await

import fetch from '../core/fetch';
 
export const path = '/products';
export const action = async () => {
  const response = await fetch('/graphql?query={products{id,name}}');
  const data = await response.json();
  return <Layout><Products {...data} /></Layout>;
};

ECMA6 harmony

特性

es6 中包含很多类似 python 的用法.

  • let, const for block scoping
  • iterator values: for (p of planets)
  • let [a, b] = ['foo', 'bar']; let {date: d, month: m} = {date: 1, month: 4};
  • [(console.log(s + “ with a ” + w + “ in the ” + r)) for (s of suspects) for (w of weapons) for (r of rooms)];
  • class, with extends, prototype, and super:
  • 更多类型:Set & Map(Map 可用任意类型作为 key)
  • function foo(bar = 'baz') {}
  • rest parameter: function push(array, …items){}; push(planets, “Mercury”, “Venus”, “Earth”, “Mars”);
  • spread parameter: function createURL (comment, path, protocol, subdomain, domain, tld) {}; createURL('haha', ['haha.html', 'http', #省略]);
  • proxies: 重载原对象的方法,如重载 set, get,达到设置对象属性就能记日志一类的作用 1)
  • generator: python 中也有,是否可以当作 “能记住自己状态并通过 yield 返回当前状态的函数” 2)
  • StructType,类似 node-struct
  • quasis, `You are ${age} years old.`, 在字符串里用变量(更像 php)
  • module
    module math {
      export function sum(x, y) {
        return x + y;
      }
      export var pi = 3.141593;
    }
     
     
    import {sum, pi} from math;
    alert(sum(pi,pi));

目前使用 es6 的方法

参考:Use ECMAScript 6 Today - Tuts+ Code Article

snippets

// 顺序无关时的数组遍历
var foo = [1, 2, 3];
 
for (var i = foo.length; i--; ) {
  console.log(foo[i]);
}

patterns 模式

module 模块模式

Javascript模块化编程(一):模块的写法 - 阮一峰的网络日志

// 使用"立即执行函数"(Immediately-Invoked Function Expression,IIFE),
// 可以达到不暴露私有成员的目的。
var module = (function(){
 
    var _count = 0;
 
    var m1 = function(){
		//...
	};
 
    var m2 = function(){
		//...
	};
 
    return {
		m1 : m1,
		m2 : m2
	};
 
})();
 
 
// 如果一个模块很大,必须分成几个部分,或者一个模块需要继承另一个模块,
// 这时就有必要采用"放大模式"(augmentation)。
var module = (function (mod){
 
    mod.m3 = function () {
		//...
    };
 
    return mod;
 
})(module);
 
 
// 独立性是模块的重要特点,模块内部最好不与程序的其他部分直接交互。
// 为了在模块内部调用全局变量,必须显式地将其他变量输入模块。
var module = (function ($, YAHOO) {
 
    //...
 
})(jQuery, YAHOO);

AMD (Asynchronous Module Definition, 异步模块定义) 和 require.js

Constructors With Prototypes

function Car( model, year, miles ) {
 
  this.model = model;
  this.year = year;
  this.miles = miles;
 
}
 
 
// Note here that we are using Object.prototype.newMethod rather than
// Object.prototype so as to avoid redefining the prototype object
Car.prototype.toString = function () {
  return this.model + " has done " + this.miles + " miles";
};
 
// Usage:
 
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
 
console.log( civic.toString() );
console.log( mondeo.toString() );

deferred

var wait = function(){
 
 var dtd = $.Deferred(); //在函数内部,新建一个Deferred对象
 var tasks = function(){
   alert("执行完毕!");
   dtd.resolve(); // 改变Deferred对象的执行状态
 };
 
 setTimeout(tasks,5000);
 
 return dtd.promise(); // 返回promise对象
};
 
$.when(wait())
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出错啦!"); });
  1. $.Deferred() 生成一个deferred对象。
  2. deferred.done() 指定操作成功时的回调函数
  3. deferred.fail() 指定操作失败时的回调函数
  4. deferred.promise() 没有参数时,返回一个新的deferred对象,该对象的运行状态无法被改变;接受参数时,作用为在参数对象上部署deferred接口。
  5. deferred.resolve() 手动改变deferred对象的运行状态为“已完成”,从而立即触发done()方法。
  6. deferred.reject() 这个方法与deferred.resolve()正好相反,调用后将deferred对象的运行状态变为“已失败”,从而立即触发fail()方法。
  7. $.when() 为多个操作指定回调函数。
  8. deferred.then(): '$.when($.ajax( “/main.php” )).then(successFunc[, failureFunc] );'
  9. deferred.always(): 这个方法也是用来指定回调函数的,它的作用是,不管调用的是deferred.resolve()还是deferred.reject(),最后总是执行。

jQuery的deferred对象详解 - 阮一峰的网络日志

currying

把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数而且返回结果的新函数的技术

In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument (partial application). It was introduced by Moses Schönfinkel and later developed by Haskell Curry.

a curried add()

// accepts partial list of arguments 
function add(x, y) {
	var oldx = x, 
		oldy = y;
	if (typeof oldy === "undefined") { // partial
		return function (newy) {
			return oldx + newy; 
		};
	}
	// full application 
	return x + y;
}
 
// test
typeof add(5); // "function" 
add(3)(4); // 7
 
// create and store a new function 
var add2000 = add(2000); 
add2000(10); // 2010

Here is the general-purpose currying function:

// Here is the general-purpose currying function:
function schonfinkelize(fn) {
	var slice = Array.prototype.slice,
		stored_args = slice.call(arguments, 1);
	return function () {
		var new_args = slice.call(arguments),
			args = stored_args.concat(new_args);
		return fn.apply(null, args);
	};
}
 
// a normal function 
function add(x, y) {
	return x + y; 
}
// curry a function to get a new function 
var newadd = schonfinkelize(add, 5);
newadd(4); // 9
// another option -- call the new function directly 
schonfinkelize(add, 6)(7); // 13
 
// The transformation function schonfinkelize() is not limited to
// single parameters or to single-step currying. Here are some more
// usage examples:
 
// a normal function
function add(a, b, c, d, e) {
	return a + b + c + d + e; 
}
// works with any number of arguments 
schonfinkelize(add, 1, 2, 3)(5, 5); // 16
// two-step currying
var addOne = schonfinkelize(add, 1);
addOne(10, 10, 10, 10); // 41
var addSix = schonfinkelize(addOne, 2, 3);
addSix(5, 5); // 16
it/javascript/start.txt · Last modified: 2016/04/24 22:57 by admin