我正在尝试在类中创建一个方法,它将实例化当前的类.但是我还需要使用此方法在所有扩展类中正常工作.正如我从这个线程中学到的,使用self关键字来完成这项任务并不好.所以明显的选择是使用static关键字.
但是,我遇到了不同的方法,也有效.
例:
class SimpleClass
{
private $arg;
public function __construct( $arg ){
$this->arg = $arg;
}
public function getArg(){return $this->arg;}
public function setArg($arg){$this->arg = $arg;}
public function staticInstance()
{
return new static( $this->arg );
}
public function thisInstance()
{
return new $this( $this->arg );
}
public function selfInstance()
{
return new self( $this->arg );
}
}
class ExtendedClass extends SimpleClass
{
}
$c1 = 'SimpleClass';
$c2 = 'ExtendedClass';
$inst1 = new $c1('simple');
$inst2 …Run Code Online (Sandbox Code Playgroud) 我想获取某个类的所有静态成员的列表。例如:我想获取所有静态成员Object(例如Object.create是否可用等)。我怎样才能做到这一点?
例子:
var ClassA = function(){}
ClassA.prototype.getName = function(){return "ClassA";} //public method
ClassA.alertName = function(){ alert("ClassA");} //static method
ClassA.doSomething = function(){return "Do something";} //another static method
Run Code Online (Sandbox Code Playgroud)
所以,如果我有更多的静态成员,我想至少得到他们的名字。在这个例子中我想得到alertName和doSomething。对于公共成员,你可以这样做:
for (i in ClassA.prototype) {
alert(i);
}
Run Code Online (Sandbox Code Playgroud)
静态成员怎么样?