Javascript -如何选择性地执行函数/语句
Javascript - How to execute function/statements selectively
不确定这是否是命名这个问题的最佳方式,但我有以下不喜欢在严格模式下运行的代码。我需要根据if
条件设置runstatementshere()
函数的内容/语句。然后runstatementshere()
将作为另一个函数的一部分运行,并成为该作用域的一部分。
if (i == true) {
function runstatementshere() {
// multiline commands
};
}
else {
function runstatementshere() {
}
}
function somecode() {
runstatementshere();
}
先看这个答案。
函数声明似乎是允许的,但在包含块中提升。我不确定这是否是定义行为,但Chrome和Firefox是这样做的。
它们的行为是这样的,因为如果这两个函数在if
语句的范围内提升,后者总是获胜。
无论如何,要解决您的问题,请使用函数表达式。
"use strict";
var runstatementshere;
if (true) {
runstatementshere = function() { console.log("a"); }
} else {
runstatementshere = function() { console.log("b"); }
}
function somecode() {
runstatementshere();
}
somecode();
最简单的方法是:
function firstFunction() {
console.log(1);
}
function secondFunction() {
console.log(2);
}
function somecode() {
if (i) {
firstFunction();
} else {
secondFunction();
}
}
var i = false;
somecode();
但是如果你有很好的理由不在somecode()
中使用if
,那么试试这种方式来声明函数。
你代码中的问题是你在同一个作用域中声明了同一个函数两次。
var runstatementshere, i = false;
if (i == true) {
runstatementshere = function() {
console.log(1);
};
} else {
runstatementshere = function() {
console.log(2);
};
}
function somecode() {
runstatementshere();
}
somecode();
这应该在严格模式下编译。但不知何故是荒谬的…因为在函数体中包含条件更符合逻辑。但是你仍然可以很好地利用它。
(function(){
var myFunction = i ? function() {} : function () {};
function a()
{
myFunction();
}}
)()
重写它,这样你就有一个函数构造器了。
var myFunctionConstructor = function(i) {
return i ? function() {} : function () {};
}
var myFunction = myFunctionConstructor(false);
myFunction(); // first function called
myFunction = myFunctionConstructor(true);
myFunction(); // second function called
相关文章:
- 如何做到这一点,使代码在不传递条件后执行函数
- javascript自执行函数-不同的语法
- JavaScript:只有当数组中的所有项都为true时才执行函数
- iFrame url更改时执行函数
- 为什么AngularJS在每个摘要循环上都执行函数
- 如何使用setInterval执行函数
- 当*ngFor以角度2结束时执行函数
- Ajax调用完成后如何执行函数
- 在显示引导弹出窗口之前执行函数
- 从自执行函数返回函数的Javascript性能命中率
- 在操作完成时执行函数
- jquery/js中的自执行函数
- 如何仅在完成对gap.client.youtube的请求.execute后执行函数
- 构造函数函数中的自执行函数的OO上下文/范围
- Javascript未使用=运算符执行函数
- AngularJS:如何按照预定义的顺序执行函数
- 在不使用隔离作用域的情况下执行函数的角度指令
- 如何在页面加载后执行函数是在 AngularJS 中完成的
- 完成页面加载后执行函数
- 如何在完成完全执行函数后触发循环