javascript如何将对象深度绑定到新的"this"值 [英] javascript how to deep bind an object to a new 'this' value

查看:55
本文介绍了javascript如何将对象深度绑定到新的"this"值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个值,该值可以是基元或函数,也可以是递归包含基元/函数/对象的对象.

I have a value which may be a primitive or a function or an object containing primitives/functions/objects recursively.

给出一个theThis参数,我如何将我值内的所有函数都深度绑定到theThis?

Given a theThis argument, how can I deep bind all functions which may be inside my value to 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 ,但这不是独立的.

I looked at some solutions like https://github.com/jonschlinkert/deep-bind/blob/master/index.js but that is not standalone.

我正在寻找独立的deepBind(val, theThis)解决方案. 我需要解决方案以同时涵盖getter和setter.

I am looking for a deepBind(val, theThis) solution which is standalone. I need the solution to also cover getters and setters.

谢谢!

推荐答案

这似乎可以按需工作

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如何将对象深度绑定到新的"this"值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆