xrea-banner xreaad

Hello, constructor!

namespace kilrey; / JavaScript / 基本 / Hello, constructor!

前のページ(Hello, object!)へ / 次のページ(Hello, scope chain!)へ

今度はコンストラクタです。 コンストラクタからオブジェクトを作るには new コンストラクタ関数 (引数...); とします。 通常の関数と異なるのは、 まずオブジェクトが作られ、 それを this としてコンストラクタ関数が実行される点です。

簡単なコンストラクタからオブジェクトを作ってみましょう。 (Hello, constructor! Sample 1)

<html>
  <head>
    <script type="text/javascript">
      var obj = new function(message){
        this.message = message;
        this.greet = function(){
          alert(this.message);
        };
      }("Hello, constructor!");
      obj.greet();
    </script>
  </head>
</html>
    

ここでは関数式をコンストラクタ関数にして オブジェクトを作っています。 obj.message にはコンストラクタ引数の "Hello, constructor!" が代入されています。 obj.greet には恒例の greet() が代入されています。

関数を作るコンストラクタもあります。 (Hello, constructor! Sample 2)

<html>
  <head>
    <script type="text/javascript">
      var greet = new Function("message","alert(message);");
      greet("Hello, constructor!");
    </script>
  </head>
</html>
    

ここでは Function 関数をコンストラクタ関数にして 関数オブジェクトを作っています。 new Function に与えた引数は 一番最後のものが関数本体に、 それ以外のものが仮引数になります。

前のページ(Hello, object!)へ / 次のページ(Hello, scope chain!)へ