【问题标题】:Javascript Class - Function Optimisation (Functions Within Functions)Javascript 类 - 函数优化(函数内的函数)
【发布时间】:2014-09-03 19:12:49
【问题描述】:

我正在定义一个类:

MyClass = function () {
    // Class member variables here
};

MyClass.prototype.MyFunction = function () {
    // Do stuff, see below
};

我不确定的是 MyFunction。这是我目前的模式(函数中的函数)。我有这种方式是因为它看起来很整洁。 MyFunctionSubFunction 仅与 MyFunction 相关联,因此从样式的角度来看,我假设 MyFunctionSubFunction 应该在 MyFunction 的定义范围内。

MyClass.prototype.MyFunction = function () {
    var i, j, iIter, jIter, a, b, c, val;
    var MyFunctionSubFunction = function (a, b, c) {
        // Do things with a, b and c
    };

    // iIter and jIter are set to values depending on what is going on

    for(i=0; i<iIter; i++) {
        for(j=0; j<jIter; j++) {
            // a, b and c are now set depending on i and j

            MyFunctionSubFunction(a, b, c);
        }
    }
};

这是一种好的编码习惯(函数中的函数)吗?

这是否针对速度和其他方面进行了优化?

MyFunction(上层函数)每秒被调用大约 250 次(它是一个游戏,这是 AI 代码的一部分)。

或者我应该这样做吗?:

MyClass.prototype.MyFunction = function () {
    var i, j, iIter, jIter, a, b, c, val;

    // iIter and jIter are set to values depending on what is going on

    for(i=0; i<iIter; i++) {
        for(j=0; j<jIter; j++) {
            // a, b and c are now set depending on i and j

            this.MyFunctionSubFunction(a, b, c);
        }
    }
};

MyClass.prototype.MyFunctionSubFunction = function (a, b, c) {
    // Do things with a, b and c
};

【问题讨论】:

    标签: javascript function class optimization


    【解决方案1】:

    MyFunction 内部定义MyFunctionSubFunction 会产生开销,因为每次调用MyFunction 都会创建一个名为MyFunctionSubFunction 的新函数。

    如果您不希望 MyFunctionSubFunction 泄漏,您可以使用 IIFE:

    (function(){
        var MyFunctionSubFunction = function (a, b, c) {
            // Do things with a, b and c
        };
        MyClass.prototype.MyFunction = function () {
            // use MyFunctionSubFunction here somewhere
        };
    })()
    

    由于MyFunctionSubFunction 直接作用于abc,它不需要是MyClass.prototype 的一部分。虽然,它可能是。

    【讨论】:

    • 谢谢。标记为已回答。 (对不起,我没有早点回来,但是在发布这个问题大约一个小时后,事情突然变得忙碌起来。)
    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多