# 即学即用系列一：纯函数

### 什么是纯函数

1. 函数的返回结果只依赖于它的参数
2. 函数执行过程中没有副作用

``````const a = 1
const impure = (b)=>a + b
impure(2) // 3``````

``````const a = 1
const pure = (x, b) => x + b
pure(1,2) //3``````

``````var values = { a: 1 };

function impureFunction ( items ) {
var b = 1;

items.a = items.a * b + 2;

return items.a;
}

var c = impureFunction( values );
values.a // 3``````

``````var values = { a: 1 };

function pureFunction ( a ) {
var b = 1;

a = a * b + 2;

return a;
}

var c = pureFunction( values.a );
values.a // 1``````

``````var array1 = [0,1,2,3,4,5,6];
var array2 = [0,1,2,3,4,5,6];

var spliceArray = array1.splice(0,2);
var sliceArray = array2.slice(0,2);

console.log('array1: ' + array1);
console.log('spliceArray: ' + spliceArray);

console.log('array2: ' + array2);
console.log('sliceArray: ' + sliceArray); ``````

``````array1: 2,3,4,5,6
spliceArray: 0,1
array2: 0,1,2,3,4,5,6
sliceArray: 0,1``````

### 非纯函数带来的副作用

``````function getName(obj){
return obj.name;
}
function getAge(obj){
return obj.age;
}
function sayHi(person){
console.log('I am' + getName(person) + ',and I am' + getAge(person) + 'years old');
}

var Tom = {
name: 'TOM',
age: 26
};

sayHi(Tom);``````

31 人关注
27 篇文章