2016-11-24 55 views
0

我有一些代碼:我怎樣才能resuse JavaScript代碼,如果它不是一個函數

//The following code is not in a function 
var a = do something 
b.vr.map.stack = a.stack; 

var s = a.stack; 
if (s instance of array) { 
}else{ 
} 

如何重新在2個不同功能的代碼?

function 1(dat){ 
    call the same code from above 
    v.load(dat) 
} 

function 2(hat){ 
call the same code from above 
change dat to hat 
v.load(hat) 
} 

1 - 如何重新使用代碼?

2 - 如何使第二功能中的dat = hat

+2

據我所知,沒有辦法做你想做的。你爲什麼不能把它變成一個功能? – nottu

+0

你可以把它放在一個函數中嗎?然後在你的下面的函數中調用它? –

回答

0

使其成爲函數。

function vload(hat_or_dat) { 
    var a = do something with hat or dat 
    b.vr.map.stack = a.stack; 

    var s = a.stack; 
    if (s instance of array) { 
    }else{ 
    } 
    return whatyoudid; 
} 

function one(dat){ 
    // call the same code from above 
    var output = vload(dat); 
    return output; 
} 

function two(hat){ 
    // call the same code from above 
    change dat to hat 
    var output = vload(hat); 
    return output; 
} 

var one_vload_result = one(mydat); 
var two_vload_result = two(myhat);