我有一个值,它可能是一个原语或一个函数或一个递归地包含原语/函数/对象的对象。
Given a theThis
参数,我如何将可能在我的值内的所有函数深度绑定到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 https://github.com/jonschlinkert/deep-bind/blob/master/index.js但这并不是独立的。
我正在寻找一个deepBind(val, theThis)
独立的解决方案。
我需要解决方案来覆盖 getter 和 setter。
Thx!
这似乎按你想要的方式工作
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)