JavaScript学習(四)


1.thisキーワード
メソッドの内部では、thisキーがメソッドを呼び出すオブジェクトになります.
  o.m();m内部では、thisはoを指す
 
内部に書かれた関数では、thisを使用してグローバルオブジェクトを指します(本質的にはグローバルオブジェクトの1つの方法ですから)
 
 
2.プロトタイプオブジェクト(継承元)
 
各オブジェクトは、プロトタイプオブジェクトのすべてのプロパティを継承します.
 
≪オブジェクト・プロパティの読み取り|Object Properties Read|emdw≫:オブジェクト自体のプロパティを先に読み、そのプロトタイプのプロパティを再読み込みしていない場合は、プロトタイプにも見つからない場合は定義されていません.
オブジェクト属性の割り当て:オブジェクト自体の属性のみが設定され、プロトタイプの属性は設定されません.
 
プロトタイプを使用すると、オブジェクトにプロパティを動的に追加できます.
 
3.Javaのクラスメカニズムを模倣する
 
// We begin with the constructor
function Circle(radius) {
    // r is an instance property, defined and initialized in the constructor.
    this.r = radius;
}

// Circle.PI is a class propertyit is a property of the constructor function.
Circle.PI = 3.14159;

// Here is an instance method that computes a circle's area.
Circle.prototype.area = function( ) { return Circle.PI * this.r * this.r; }

// This class method takes two Circle objects and returns the
// one that has the larger radius.
Circle.max = function(a,b) {
    if (a.r > b.r) return a;
    else return b;
}

// Here is some code that uses each of these fields:
var c = new Circle(1.0);      // Create an instance of the Circle class
c.r = 2.2;                    // Set the r instance property
var a = c.area( );             // Invoke the area( ) instance method
var x = Math.exp(Circle.PI);  // Use the PI class property in our own computation
var d = new Circle(1.2);      // Create another Circle instance
var bigger = Circle.max(c,d); // Use the max( ) class method
 
 
4.オブジェクトの属性と方法
 
constructorプロパティ:プロトタイプオブジェクトから継承されたコンストラクション関数を参照します.
しかし、constructorプロパティが常に存在することは保証されません.このプロトタイプオブジェクトのプロパティリファレンスが置き換えられるからです.JavaScript1.1の中は読み取り専用で、後に書くことができるようになって、どんな原因を知りません.
 
if ((typeof o == "object") && (o.constructor == Date))
    // Then do something with the Date object...
 
 
上記の機能はinstanceofでも実現できます.
 
if ((typeof o == "object") && (o instanceof Date))
    // Then do something with the Date object...