在PHP中,字符串可用于动态选择用于实例化的类.以下是PHP中的两个简单类:
PHP
class Magic implements Genius {
public function perform() {
echo 'madya look :P' . PHP_EOL;
}
}
class Genie implements Genius {
public function perform() {
echo 'your wish has been granted!' . PHP_EOL;
}
}
现在可能存在一个变量,使得在运行时实例化的类基于其内容
$sGeniusClass = 'Magic';
$oGenius = new $sGeniusClass();
现在在Javascript中我喜欢使用函数作为构造函数来获得某种级别的类型,在这种情况下我可能会:
function Magic() {}
Magic.prototype = {
perform : function()
{
console.log('madya look :P');
}
}
function Genie() {}
Genie.prototype = {
perform : function()
{
console.log('your wish has been granted!');
}
}
我知道我可以使用eval来实现与PHP类似的东西:
方法#1
var sClassName = 'Genie';
eval('var oGenius = new ' + sClassName);
我也见过调用Function函数的an approach:
方法#2
var sClassName = 'Genie';
var oGenius = new Function('return new ' + sClassName)();
On the MDN虽然听起来每次创建实例时都会因重新评估而影响性能:
Function objects created with the Function constructor are parsed when
the function is created. This is less efficient than declaring a
function and calling it within your code,because functions declared
with the function statement are parsed with the rest of the code.
现在我还有一种方法有点单调乏味:
方法#3
var aClassMap = {
Magic : Magic,Genie : Genie,create : function(sClassName) {
if(this[sClassName] === undefined)
return false;
return new this[sClassName];
}
}
var sClassName = 'Genie';
var oGenius = aClassMap.create(sClassName);
这似乎是我最喜欢的整体,没有使用eval,也没有后续的重新评估,比如解决方案#2.虽然这仍然有点工作,所以我的问题是双重的:
最佳答案
原文链接:https://www.f2er.com/js/429530.html