19-12-10 JS的AOP JSON.stringify()进阶 js解析与反解析

165 阅读1分钟

JS的AOP,暂时没想到用处

Function.prototype.before = function() {
    const __self = this;
    return function(...args) {
        console.log('hi, ihap is watching before you!');
        return __self.apply(this, args);
    }
}

const cat = {
    eat: function() {
        console.log('my cat is eatting!');
    }.before(),
};

cat.eat();
// hi, ihap is watching before you!
// my cat is eatting!

JSON.stringify()进阶

  1. 对象属性桥接
const mapObj = {
  _id: "id",
  created_at: "createdAt",
  updated_at: "updatedAt"
};

JSON.parse(
  JSON.stringify(todayILearn).replace(
    /_id|created_at|updated_at/gi,
    matched => mapObj[matched])
)

// { 
// id: 1,
//  content: '今天学习 JSON.stringify(),我很开心!',
//  createdAt: 'Mon Nov 25 2019 14:03:55 GMT+0800 (中国标准时间)',
//  updatedAt: 'Mon Nov 25 2019 16:03:55 GMT+0800 (中国标准时间)' 
// }
  1. undefined、任意的函数以及 symbol 作为对象属性值时 JSON.stringify() 将跳过(忽略)对它们进行序列化,它们作为数组元素会被序列化为 null
  2. 如果要转化的对象定义了 toJSON 方法,那么 JSON.stringify() 的值是 toJSON方法的返回值

js解析与反解析

@babel/parser 是负责解析 js语法的工具,可以理解为将 js语法转化为 ast
@babel/generator 用于将 @babel/parser 解析出的 ast 转化回字符串形式的 js代码