2017-09-29 26 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

請注意遞歸綁定沒有多大意義,因爲人們希望通過其調用站點來定義詞法上下文。

相關問題