我有一个值,该值可以是基元或函数,也可以是递归包含基元/函数/对象的对象。
给定一个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之类的一些解决方案,但这并不是独立的。
我正在寻找独立的
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();