最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I conditionally define a function in javascript? - Stack Overflow

programmeradmin2浏览0评论

Consider the following script:

if (false)​ {
    function foo() {
        alert("FOO");
    }
}
foo(); // alerts "FOO"

As you can see, the function foo is defined and works even though the condition for the if fails.

The reason I want to do this is that I am developing an extension for InDesign and I made a script called utilities.jsx which holds various functions which are used in other scripts. In all the scripts that need these functions, I simply use:

app.doScript(File(scriptsFile.parent.fsName + "/t_utilities.jsx"), ScriptLanguage.JAVASCRIPT);

which defines all the functions I need and then I can use them. Now, since this script will be called multiple times by various files in an unpredictable order (the user decides), I thought I might only define the functions if they haven't been defined before (if utilities.jsx hasn't run yet). Kind of like require_once in php.

I was thinking of something like the following, but that doesn't work as the functions are defined every time the script is run:`

var utilitiesHasRun;
if (utilitiesHasRun !== true) {
  // define all the functions
  // ...
  utilitiesHasRun = true;
}

Are there any other options?

Consider the following script:

if (false)​ {
    function foo() {
        alert("FOO");
    }
}
foo(); // alerts "FOO"

As you can see, the function foo is defined and works even though the condition for the if fails.

The reason I want to do this is that I am developing an extension for InDesign and I made a script called utilities.jsx which holds various functions which are used in other scripts. In all the scripts that need these functions, I simply use:

app.doScript(File(scriptsFile.parent.fsName + "/t_utilities.jsx"), ScriptLanguage.JAVASCRIPT);

which defines all the functions I need and then I can use them. Now, since this script will be called multiple times by various files in an unpredictable order (the user decides), I thought I might only define the functions if they haven't been defined before (if utilities.jsx hasn't run yet). Kind of like require_once in php.

I was thinking of something like the following, but that doesn't work as the functions are defined every time the script is run:`

var utilitiesHasRun;
if (utilitiesHasRun !== true) {
  // define all the functions
  // ...
  utilitiesHasRun = true;
}

Are there any other options?

Share Improve this question asked Jun 14, 2012 at 14:15 ShawnShawn 11.4k21 gold badges85 silver badges139 bronze badges 2
  • 2 Your first code snippet isn't technically valid because function declarations aren't allowed within blocks. It only works at all because all major browsers implement extensions to the ECMAScript spec to deal with this case. – Tim Down Commented Jun 14, 2012 at 14:20
  • And to continue @TimDown's comment, your first snippet will actually throw a SyntaxError if it's part of strict mode code. – James Allardice Commented Jun 14, 2012 at 14:55
Add a comment  | 

4 Answers 4

Reset to default 20

You can make them function expressions instead of function declarations:

if (false)​ {
    var foo = function () {
        alert("FOO");
    };
}
foo(); //TypeError: undefined is not a function

Note that in the above code, foo is still accessible even though the condition evaluated to false. This is because function-scoped declarations (both function and var) are hoisted to the top of the scope in which they are declared. However, assignments happen at the point in the code where they appear.

What the above code is effectively doing is this:

var foo; //No assignment, foo is undefined
if (false)​ {
    foo = function () {
        alert("FOO");
    };
}
foo(); //TypeError: undefined is not a function

Warning - Named function expressions are still hoisted in Internet Explorer 8 and below (this is a bug in IE). Obviously this is only a potential problem if you need to support old browsers.

To assure your function has not been defined before, use :

if ( typeof yourFunctionName == 'undefined' ) {
  yourFunctionName = function( params ) {
    // your code here
  };
}

You can use function pointers to reassign the function as needed.

var myFunctionPointer = function { alert("Default"); };
if (condition) {
    myFunctionPointer = function { alert("true"); };
}
else {
    myFunctionPointer = function { alert("false"); };
}
myFunctionPointer();

Usually I create a full API based on a function that return an object containing methods which are finally call to the minor JS functions. Extensions can interact with JS files with an embedded class. I think I gave you the link to the cookbook. So what you can do is declare an object in AS3 and check for some property like :

public var jsAPI:Object = {};

the js code would be

var jsAPI = function() {
    return {
        hasBeenLoaded:false,
        myMethod1:function(){},
    }
}

Then if you need to use a JS function in AS3, you can check some flag like :

if ( jsAPI.hasBeenLoaded ){ … }
else { //loads the API via new API() }
发布评论

评论列表(0)

  1. 暂无评论