在 PHP 中,可以使用字符串来动态选择要实例化的类。这里有 2 个简单的 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);
我也看过 an approach调用 Function 函数:
方法 #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。尽管如此,它仍然需要一些工作,所以我的问题是双重的:
- 除了我展示的 3 种方法之外,还有其他方法可以做到这一点吗?
- 是否有类似于 PHP 的东西,其中字符串可以映射到要实例化的函数?
最佳答案
我认为您涵盖了所有内容。但是,您可以通过记住全局变量和函数是窗口对象的属性来简化第三种方法,因此您可以使用 window
创建全局类,如下所示:
var myClassName = "Genie";
window[myClassName] = function {};
window[myClassName].prototype = {
perform : function()
{
console.log('I am a ' + myClassName + ', and your wish has been granted!');
}
}
我认为性能会一如既往地好(因为 Javascript 在内部使用哈希表来引用对象属性,无论如何)。
关于php - 来自动态函数名称的 Javascript 新对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9222172/