如果它不是一个函数,我怎么能重新使用javascript代码

时间:2016-11-24 21:09:15

标签: javascript jquery arrays function object

我有一些代码:

//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

1 个答案:

答案 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);