2017-09-29 24 views
0

我有一个值,它可能是一个基元或一个函数或一个包含基元/函数/对象递归的对象。javascript如何将一个对象深度绑定到一个新的“this”值

鉴于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。

Thx!

+1

'我看了一些解决方案,并做了一些失败的尝试,但没有运气......比如? –

+0

_“或递归地包含原始类型/函数/对象的对象”_你是什么意思“递归”? – guest271314

+0

添加我的尝试 – kofifus

回答

1

这似乎只要你想

function deepBind(o, ths) { 
 
    Object.entries(o).forEach(([key, value]) => { 
 
     if (typeof value === "function") { 
 
      // don't use value here :p 
 
     \t o[key] = o[key].bind(ths); 
 
     } 
 
     if (typeof value === 'object' || typeof value === 'function') { 
 
     \t 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();

+0

伟大,这也会覆盖获取/设置属性? – kofifus

+0

我还没有最初的想法:p –

+0

_“这也会覆盖get/set属性吗?”_原始问题中提及的get和set属性在哪里?请参阅https://stackoverflow.com/help/how-to-ask – guest271314

0

沿东西线的工作:

function deepBind (o, thisVal) { 

    return Object.keys(o) 
     .reduce((res, key) => { 

      const v = o[key]; 
      const tv = typeof v; 
      switch (tv) { 
       case "object": 
        // should be updated for arrays... 
        if (v !== null) { 
         res[key] = deepBind(v, thisVal); 
        } else { 
         res[key] = v; 
        } 
        break; 
       case "function": 
        res[key] = v.bind(thisVal); 
        break; 
       default: 
        res[key] = v; 
        break; 
      } 
      return res; 

     }, {}); 

} 

它递归地从原始对象的值复制,装订功能道具thisVal

请注意递归绑定没有多大意义,因为人们希望通过其调用站点来定义词法上下文。

相关问题