練炭ブログ

萌え壁紙、Irvine、DMonkey、Proxomitron などの情報を扱ってます。

DMonkey: 変数経由のnew演算子

コメントなし»
function Foo () {
  alert ('Foo constructor');
}
Foo.prototype.p = function () {
  alert ("this is Foo\nnameOf = " + nameOf (this));
};

function Baz () {
  alert ('Baz constructor');
}
Baz.prototype.p = function () {
  alert ("this is Baz\nnameOf = " + nameOf (this));
};

function test () {
  var f = new Foo ();  // Foo constructor
  f.p ();  // this is Foo, nameOf = Foo

  var Bar = Foo;
  var f2 = new Bar ();  // Foo constructor
  try { f2.p (); } catch (e) { alert (e); }  // ENameError

  var Baz = Foo;
  var f3 = new Baz ();  // Foo constructor
  f3.p ();  // this is Baz, nameOf = Baz
}
test ();

変数に関数を代入してその変数名で new すると、参照している関数がコンストラクタとして呼び出されますが、prototype として使われるのはその変数名と同名の関数の prototype になってしまいます。

名前付き関数式はグローバルスコープに対する関数宣言として動作する の末尾のエラー例も、これと同じことだと思います。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です