ラベル JavaScript の投稿を表示しています。 すべての投稿を表示
ラベル JavaScript の投稿を表示しています。 すべての投稿を表示

2013年1月29日火曜日

Debug Message

[ダイアログを出す]
 alert( "Debug Message" );
[コンソールに出力]
 console.log( "Debug Message" );
 console.error( "Error Message" );
 console.warn( "Warning Message" );
ダイアログをいちいち消す必要がないのでコンソールに出した方がラクチン

JavaScript実験用HTML

JavaScriptの実験をするためだけの最小限のHTML
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
 <title>JavaScriptTest</title>
 <script type="text/javascript">
  JavaScriptコード
 </script>

オブジェクト・プリミティブへの代入実験

 var a = [ 0, 1, 2 ];
 alert( a.length ); // 3

 a[ 3 ] = 3;
 alert( a.length ); // 4
 var a = 3;
 var b = a;
 alert( "a = " + a ); // a = 3
 alert( "b = " + b ); // b = 3

 a = 5;
 alert( "a = " + a ); // a = 5
 alert( "b = " + b ); // b = 3
 var a = new Object();
 a.property = 10;

 var b = new Object();
 b = a;

 alert( "a.property = " + a.property ); // a.property = 10
 alert( "b.property = " + b.property ); // b.property = 10

 a.property = 5;
 alert( "a.property = " + a.property ); // a.property = 5
 alert( "b.property = " + b.property ); // b.property = 5 !!!

 b.property = 8;
 alert( "a.property = " + a.property ); // a.property = 8 !!!
 alert( "b.property = " + b.property ); // b.property = 8
 var a = { property : 10 };
 var b = a;
 alert( "a.property = " + a.property ); // a.property = 10
 alert( "b.property = " + b.property ); // b.property = 10

 a.property = 5;
 alert( "a.property = " + a.property ); // a.property = 5
 alert( "b.property = " + b.property ); // b.property = 5 !!!

 b.property = 8;
 alert( "a.property = " + a.property ); // a.property = 8 !!!
 alert( "b.property = " + b.property ); // b.property = 8
  • オブジェクト : 変数に代入したとき、その実体ではなく参照が代入される
  • プリミティブ : 実体がそのまま代入される

プロパティの書き方

 var a = new Object();
 a.property1 = 1; // オブジェクト名.プロパティ名 = 値
 a.property2 = 2;
or
 var a = {
  property1 : 1, // プロパティ名 : 値
  property2 : 2,
 };

2013年1月28日月曜日

JavaScriptでクラス継承

JavaScriptでクラスの継承をするには、
 var car = function(){};
 car.prototype = {
  run:function(){
   alert( "走る" );
  }
 };

 var truck = function(){};
 truck.prototype = new car();
 truck.prototype.carry = function(){
  alert( "運ぶ" );
 };

 var truck1 = new truck();
 truck1.run();
 truck1.carry();
とすればOK

2013年1月24日木曜日

JavaScriptでクラス作成

JavaScriptはプロトタイプベースのオブジェクト指向言語なので、クラスという概念はないらしいが、new演算子とコンストラクタ・プロトタイプを使うことでクラスのようなものを作れるようなので、そのメモ。

[コンストラクタ]
 var car = function(){};

[メンバ変数]
メンバ変数にはthisを付ける。
 var car = function( _maker, _color ){
  this.maker = _maker;
  this.color = _color;
 };

[メンバ関数]
 var car = function( _maker, _color ){
  this.maker = _maker;
  this.color = _color;
 };
 car.prototype = {
  getColor : function(){
   alert( "この車の色は" + this.color + "です。" );
  }
 }

[使用例]
 var car = function( _maker, _color ){
  this.maker = _maker;
  this.color = _color;
 };
 car.prototype = {
  getColor : function(){
   alert( "この車の色は" + this.color + "です。" );
  }
 }

 var myCar = new car( "toyota", "white" );
 myCar.getColor();