JavaScript Core Object | Object 物件(Object Object)
Object 物件(Object Object)
| Object 物件 | 兼容性:IE3+、NN2+、Moz1+、Safari1+ |
objName = new Object()
objName:物件名稱
| 屬 性 | constructor、prototype |
| 方 法 | toString()、valueOf() |
Object 物件在 JS 的環境當中,它是 JS 原始的物件類型,並且也是一個重要的內建物件;所有的 JS 物件都是從 Object 衍生出來的,也就是說它是其它內建物件的根物件。並且它也是我們自訂物件的一個基礎元件。
//範例
myObj = new Object("嗨~您好");//建立與初始化 myObj
document.write(myObj); //其結果顯示 嗨~您好
通用的物件屬性和方法(Universal Object Properties And Methods)
| prototype 物件 屬性 | 兼容性:IE4+、NN3+、Moz1+、Safari1+ |
objName.prototype.pName = theValue
objName:物件名稱pName:新的屬性名稱theValue:設定值
JS 的每個物件都有一個 prototype 屬性,這個屬性代表著事先所定義的原型物件(Prototype Object)。
當我們使用 prototype 於某個物件後,屬於這個 prototype 物件的所有屬性或方法,都將可以被該物件的實體(或稱副本)所繼承。
這可以用來表示物件的原型或者讓我們對任何一個物件來增加自訂的屬性和方法。
//範例一 String.prototype.myP = "Hi"; //修改了 String 物件的原型(加上了 myP 屬性) myStr = new String(); //建立與初始化 myStr document.write(myStr.myP); //其顯示結果為 Hi
//範例二
//建立 myRect 建構式函式來定義 myRect 物件
function myRect(rectWidth, rectHeight) {
this.width = rectWidth; //使用參數 rectWidth 初始化 this 所指向的屬性 width
this.height = rectHeight; //使用參數 rectHeight 初始化 this 所指向的屬性 height
}
//對之後的每個物件實體(副本)增添 area 方法並回傳參數相乘的結果
myRect.prototype.area = function() {
return this.width * this.height;
}
//呼叫 myRect 建構式函式並且使用 new 來建立物件的實體(副本)
var Rect1 = new myRect(1, 2); //這時 Rect1 = { width:1, height:2 };
var Rect2 = new myRect(3, 4); //這時 Rect2 = { width:3, height:4 };
//呼叫所共享的 area() 來計算先前所傳入的參數值並顯示
document.write(Rect1.area()); //結果為 2
document.write(Rect2.area()); //結果為 12
| constructor 屬性 | 兼容性:IE4+、NN4+、Moz1+、Safari1+ |
objName.constructor
objName:物件名稱
JS 的每個物件都有一個 constructor 屬性,用來指向物件的建構式。
這個屬性可以用來傳回或判斷物件的類型。
//範例一
myArrObj = new Array();
myDateObj = new Date();
document.write("物件的類型為: " + myArrObj.constructor);
//▲ 其結果顯示 物件的類型為: function Array() { [native code] }
document.write("物件的類型為: " + myDateObj.constructor);
//▲ 其結果顯示 物件的類型為: function Date() { [native code] }
//範例二
var myStr = new String();
if (myStr.constructor == String) { //判斷 myStr 是否為 String 物件
document.write("true"); //結果顯示為 true
}
| toString() 方法 | 兼容性:IE4+、NN4+、Moz1+、Safari1+ |
objName.toString()
objName:物件名稱
這個方法是用來回傳一個字串來表示一個指定的物件,也就是轉換指定的物件為字串,並且將其結果傳回。
//範例一 var myObj = new Object(); document.write(myObj.toString()); //結果顯示 [object Object]
//範例二
function myRect(rectWidth, rectHeight) {
this.width = rectWidth;
this.height = rectHeight;
}
myRect.prototype.area = function() {
return this.width * this.height;
}
myRect.prototype.toString = function() {
return "寬為" + this.width + "長為" + this.height + "的面積為" + this.area();
}
var Rect1 = new myRect(1, 2);
document.write(Rect1.toString()); //寬為1長為2的面積為2
| valueOf() 方法 | 兼容性:IE4+、NN4+、Moz1+、Safari1+ |
objName.valueOf()
objName:物件名稱
這個方法是用來回傳一個我們所指定物件的原始值。
//範例
document.write(Date.valueOf());
//其顯示結果為 function Date() { [native code] }




