夕顔 | 骚操作合集

reducer 里,如果我们想删除一项,进行如下操作。妈妈再也不用担心我拷贝对象了。

1
2
3
4
5
6
7
8
9
10
11
const removeQuestion = (state, action) => {
const { id } = action.payload;

// 正常操作
const newState = Object.assign({}, state);
delete newState[id];
return newState;
};

// 骚操作
return (({ [id]: deleted, ...newState }) => newState)(state);

此处巧妙地运用解构赋值对对象的属性进行过滤。


看高阶函数的时候对下面一段代码印象深刻。实在精妙。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Function.prototype.before = function(beforefn) {
const __self = this; // this -> func
return function() {
// this -> window
beforefn.apply(this, arguments);
return __self.apply(this, arguments); // 调用func 返回值为func()的返回值
};
};

Function.prototype.after = function(afterfn) {
const __self = this; // this -> 即调用 func.before返回的函数
return function() {
// [入口] this -> window
const ret = __self.apply(this, arguments); // window调用 func.before返回的函数 ret为func()的返回值
afterfn.apply(this, arguments); // window调用afterfn
return ret; // [出口]返回func()的返回值
};
};

let func = function() {
console.log(2);
return "i am ret";
};

func = func
.before(function() {
console.log(1);
})
.after(function() {
console.log(3);
});

func();

微博上一段子

1
2
console = Math;
console.log(1); // 0

还记得大明湖畔的对数吗


Yiga 代码中的一段操作

1
2
3
4
5
6
7
8
9
10
render() {
const { children, color, style, fontColor, ...props } = this.props
return(
<TouchableOpacity {...props}>
<View style={[styles.container, { background: color }, style]}>
<Text style={[styles.text, {color: fontColor}]}>{ children }</Text>
</View>
</TouchableOpacity>
)
}

这段代码里剩余参数的用法可谓是解构赋值的非常骚的操作。

如何优雅的要钱