gpt4 book ai didi

javascript - 如何修改对象中每个函数的行为?

转载 作者:行者123 更新时间:2023-12-03 16:27:36 25 4
gpt4 key购买 nike

现在我有一个对象,比如这支笔。

类的原型(prototype)包含一系列函数和其他属性。

var Pen = function(){
this.inkColor = 'red';

this.write = function(text){
document.write(text);
}

this.refill = function(){
console.log('refilling');
}

this.getInkColor = function(){
return this.inkColor;
}

};

var pen = new Pen();
pen.write(pen.getInkColor() + ': Hello');

有没有办法避免修改 Pen 类,但改变它拥有的每个函数的行为,例如在实际函数调用之前打印日志?

this.write = function(text){
// do something first
document.write(text);
}

this.refill = function(){
// do something first
console.log('refilling');
}

this.getInkColor = function(){
// do something first
return this.inkColor;
}

最佳答案

您可以将笔包裹在 Proxy 中并定义适当的处理程序。

var Pen = function(){
this.inkColor = 'red';

this.write = function(text){
document.write(text);
}

this.refill = function(){
console.log('refilling');
}

this.getInkColor = function(){
return this.inkColor;
}

};

var handler = {
get: function(target, name) {
return name in target ? function (...args) {console.log('Hello World'); return target[name](args)} : undefined;
}
};


var pen = new Pen();
var p = new Proxy(pen, handler);
p.write(p.getInkColor() + ': Hello');

关于javascript - 如何修改对象中每个函数的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52292745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com