简体   繁体   English

闭包和解构—重构的函数不能互相调用?

[英]Closures & Destructuring — Destructured functions can't call each other?

I have something like the following: 我有类似以下内容:

let MM = {
    a: function(){
        b();
    },
    b: function(){
        console.log('b');
    }
};

function makeClosure(M) {
    let { a, b } = M;

    function a2(){ b2() };
    function b2(){ console.log('b2'); };

    return function( arg ){
        if ( arg === 1 ) a();
        if ( arg === 2 ) a2();
    }
}

let c = makeClosure( MM );

////////////////////////////////////////////
// RESULTS

c( 1 ); // b() doesn't exist
c( 2 ); // b2() exists just fine

 let MM = { a: function(){ b(); }, b: function(){ console.log('b'); } }; function makeClosure(M) { let { a, b } = M; function a2(){ b2() }; function b2(){ console.log('b2'); }; return function( arg ){ if ( arg === 1 ) a(); if ( arg === 2 ) a2(); } } let c = makeClosure( MM ); //////////////////////////////////////////// // RESULTS c( 1 ); // b() doesn't exist c( 2 ); // b2() exists just fine 

Why do the above Results outcomes happen? 为什么会出现上述结果结果? I thought destructuring was supposed to be equivalent to declaration. 我认为解构应该等同于声明。 Why is the destructured b not found by a? 为什么a找不到变形的b? They exist in the same scope? 它们存在于同一范围内吗?

Is there any way to make this work? 有什么办法可以使这项工作吗? I would prefer to destructure for organizational reasons. 由于组织原因,我宁愿进行销毁。 I can't keep them as methods for various reasons. 由于种种原因,我不能将它们保留为方法。

There is no standalone function named b from the lexical scope of MM.a , so calling a() from makeClosure results in an error because no variable or function named b can be found from within the a function in MM . MM.a的词法范围中没有名为b独立函数,因此从makeClosure调用a() makeClosure导致错误,因为在MMa函数中找不到名为b变量或函数。

One possibility would be to pass a the function to execute, that way MM doesn't rely on any outer variable: 一种可能性是传递a函数来执行,这样MM不会依赖任何外部变量:

 let MM = { a: function(someFn){ someFn(); }, b: function(){ console.log('b'); } }; function makeClosure(M) { let { a, b } = M; function a2(){ b2() }; function b2(){ console.log('b2'); }; return function( arg ){ if ( arg === 1 ) a(b); if ( arg === 2 ) a2(); } } let c = makeClosure( MM ); c(1); c(2); 

Another option would be to call a inside makeClosure with a calling context of an object which has a b property, just like MM , and have MM.a call this.b : 另一种选择是,以call a内部makeClosure与具有对象的调用上下文b财产,就像MM ,并有MM.a调用this.b

 let MM = { a: function(){ this.b(); }, b: function(){ console.log('b'); } }; function makeClosure(M) { let { a, b } = M; function a2(){ b2() }; function b2(){ console.log('b2'); }; return function( arg ){ if ( arg === 1 ) a.call({ b }); if ( arg === 2 ) a2(); } } let c = makeClosure( MM ); c(1); c(2); 

The issue doesn't have anything to do with destructuring - it's just plain JS scoping rules. 这个问题与解构无关,只是简单的JS作用域规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM