I am wondering which way it is to integrate a function... I put 4 methods below. Is one or the other better because of variable scopes, and/or ways of declaring? Maybe some or all of them are completely wrong? Any help is appreciated. Thank you so much!

//method 1
var derpHerp1 = function() {
    var addMe1 = function (firstNum,secNum){
        var sum = firstNum + secNum;
        return sum
    }
    return {
        derp : 'derp',
        herp : function(){
            alert('herp');
        },
        adding : addMe1(5,6)
    }
}();

//method 2 (2nd line & 3rd to the last changed)
var derpHerp2 = function() {
    var addMe2 = function addMe2(firstNum,secNum){
        var sum = firstNum + secNum;
        return sum
    }
    return {
        derp : 'derp',
        herp : function(){
            alert('herp');
        },
        adding : addMe2(5,6)
    }
}();

//method 3 (2nd line & 3rd to the last changed)
var derpHerp3 = function() {
    function addMe3(firstNum,secNum){
        var sum = firstNum + secNum;
        return sum
    }
    return {
        derp : 'derp',
        herp : function(){
            alert('herp');
        },
        adding : addMe3(5,6)
    }
}();

//method 4 
function addMe4 (firstNum,secNum){
            var sum = firstNum + secNum;
            return sum
}

var derpHerp4 = function() {
    return {
        derp : 'derp',
        herp : function(){
            alert('herp');
        },
        adding : addMe4(5,6)
    }
}();
有帮助吗?

解决方案

I would just do this

function f1(a, b) {
    ...
}

function f2() {
    ...
}

obj = {
    derp : 'derp',
    herp : (f1),
    adding : (f2)(5,6)
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top