gpt4 book ai didi

javascript 如何将对象深度绑定(bind)到新的 'this' 值

转载 作者:行者123 更新时间:2023-11-30 15:01:25 25 4
gpt4 key购买 nike

我有一个值,它可以是基元或函数或递归地包含基元/函数/对象的对象。

给定一个 theThis 参数,我如何才能将所有可能在我的值内的函数深度绑定(bind)到 theThis

我试过类似的方法:

function deepBind(o, ths) { 
Object.getOwnPropertyNames(o).forEach(key => {
const desc=Object.getOwnPropertyDescriptor(o, key);
if (typeof desc === "function") Object.defineProperty(o, key, key.bind(ths));
if (Object.getOwnPropertyNames(key).length>0) deepBind(o.key, ths);
});
}

但是失败了:(

我查看了一些解决方案,例如 https://github.com/jonschlinkert/deep-bind/blob/master/index.js但这不是独立的。

我正在寻找一个独立的 deepBind(val, theThis) 解决方案。我需要解决方案来涵盖 getter 和 setter。

谢谢!

最佳答案

这似乎如你所愿

function deepBind(o, ths) {
Object.entries(o).forEach(([key, value]) => {
if (typeof value === "function") {
// don't use value here :p
o[key] = o[key].bind(ths);
}
if (typeof value === 'object' || typeof value === 'function') {
deepBind(value, ths);
}
});
}
const v = {
foo:3,
fn: function() {
console.log(this);
},
obj: {
bar: 4,
fn: function() {
console.log(this);
}
}
};
var someThis = {hello: 'world'};
deepBind(v, someThis);
v.fn();
v.obj.fn();

关于javascript 如何将对象深度绑定(bind)到新的 'this' 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46480351/

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