関数を一時的に使用したい場合、関数リテラルを使用することができます。
関数リテラルは以下の形をしています。
識別子 = function (引数1, 引数2, ... , 引数n) { ブロック };
通常の関数定義とほとんど同じ構文ですが、関数名が無く、関数を識別子に代入する形になっています。
var move = function (speed) {// 関数リテラルで定義
ball._x+=speed*Math.cos(ball._rotation/180*Math.PI); ball._y+=speed*Math.sin(ball._rotation/180*Math.PI); } move(10);// 関数の実行
関数リテラルはクラスやオブジェクトにメソッドを代入するときに使用します。
オブジェクト名.メソッド名 = 関数リテラル;
ball.move = function (speed) {// 関数リテラルで定義
this._x+=speed*Math.cos(this._rotation/180*Math.PI); this._y+=speed*Math.sin(this._rotation/180*Math.PI); } ball.move(10);// 関数の実行
関数を使ったメソッドの定義もできます。
オブジェクト名.メソッド名 = 関数;
function move(speed) {// 関数で定義
this._x+=speed*Math.cos(this._rotation/180*Math.PI); this._y+=speed*Math.sin(this._rotation/180*Math.PI); } ball.move=move;// メソッドの定義
ball.move(10);// 関数の実行
上記の関数リテラルを使った場合との違いは、ball.move()メソッドの他にmove()関数が残ることです。
Programming Laboratory (Shio seminar)