2015-10-07 33 views
3

內:的Javascript返回了功能鑑於這種代碼的函數

var x=5; 
var fx=function(){ 
    console.log("hey"); 
    (function(){ 
     if (x==5){ 
      console.log('hi'); 
      return; 
     } 
    })(); 
    console.log('end'); 
}; 

fx(); 

我如何以這樣的方式返回,最終console.log不執行時x==5

我是新來的JavaScript,所以也許我錯過了什麼......

+1

我只是好奇你爲什麼要這個 – JSelser

+0

這只是我編造的一個案例,用來作爲我正在處理的更復雜的代碼的示例,但它遵循類似的模式。 – Academiphile

回答

1

您不能返回這樣的,而不是你可以使用一個標誌,或使內部函數返回像

var x = 5; 
 
var fx = function() { 
 
    snippet.log("hey"); 
 

 
    var flag = (function() { 
 
    if (x == 5) { 
 
     snippet.log('hi'); 
 
     return false; 
 
    } 
 
    })(); 
 
    //if the returned value is false then return 
 
    if (flag === false) { 
 
    return 
 
    } 
 
    snippet.log('end'); 
 
}; 
 

 
fx();
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

0

var x = 5; 
 
var fx = function() { 
 
    console.log("hey"); 
 

 
    if (x == 5) { 
 
    console.log('hi'); 
 
    return; 
 
    } 
 

 
    console.log('end'); 
 
}; 
 

 
fx();

0

您可以if語句或其他取決於hwta你正在試圖做的

如果

var x=5; var fx=function(){ 
    console.log("hey"); 
    (function(){ 
     if (x==5){ 
      console.log('hi'); 
      return; 
     } 
    })(); 
    if(x != 5){ 
     console.log('end'); 
    } }; 

fx(); 

其他

var x=5; 
var fx=function(){ 
    console.log("hey"); 
    (function(){ 
     if (x==5){ 
      console.log('hi'); 
      return; 
     } else { 
      console.log('end'); 
     } 
    })(); 
}; 

fx(); 
1

你可以用你的函數的條件

var x=5; 
var fx=function(){ 
    console.log("hey"); 
    if(!(function(){ 
     if (x==5){ 
      console.log('hi'); 
      return true; 
     } 
    })()){ 
     console.log('end'); 
    } 
}; 

fx(); 

JSFIDDLE DEMO