Proxy Hook Trace JSON

2023-12-14 09:40:57

Proxy

var window = {
    key: "qww",
    age: 22
}
window = new Proxy(window, {
    get(target, p, receiver) {
        console.log("target: ", target);
        console.log("p: ", p);
        // return window['username'];/// 这里如果这样写. 有递归风险的...
        // return Reflect.get(...arguments);
        return Reflect.get(target, p);
    },
    set(target, p, value, receiver) {
        console.log("设置操作")
        Reflect.set(target, p, value);
    }
}); 

console.log(window.username);
console.log(window.age);
window.username = "qww_qww"
window.age = 18
function use_proxy(obj) {
    return new Proxy(obj, {
        get(target, p, receiver) {
            let val = Reflect.get(...arguments);
            console.log("<<==:", "get("+ p+ ")", "return_val=" + val, target);
            return val;
        },
        set(target, p, value, receiver) {
            console.log("==>>: ",  p +".set("+ value +")", target);
            return Reflect.set(...arguments);
        }
    });
}

// 
window = use_proxy(window)

Hook

function foo(a, b, c, d, e, f) {
    console.log("foo功能...")
    console.log(a, b, c, d, e, f)
    return 123
}

var _foo = foo

foo = function () {
    console.log("begin hook")
    // _foo(arguments)
    _foo.apply(this,arguments)
    console.log("end Hook")
}

foo(1,2,3,4,5,6,7)

Trace

const traceProperty = (object, property) => {
	let value = object[property];
	Object.defineProperty(object, property, {
		get() {
			console.trace(`${property} requested`);
			return value;
		},
		set(newValue) {
			console.trace(`setting ${property} to `, newValue);
			value = newValue;
		}
	});
};

//

var foo = {
    name: '张三',
};

Object.defineProperty(foo, 'age', {
    get: function () {
        console.log('==>> get');
        return count;
    },
    set: function (val) {
        console.log('==>> set ');
        count = val + 1;
    },
});

foo.age = 18;
console.log(foo.age);

JSON 解除循环引用

window.json_to = function (params) {
    let cache = [];
   return JSON.stringify(params, function (key, value) {
        if (typeof value  === 'object' && value !== null) {
            if (cache.indexOf(value) !==  -1) {
                return;
            }
            cache.push(value);
        }
        return value;
    });
}

文章来源:https://blog.csdn.net/wwq921220/article/details/134916117
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。