一個對象構造器只不過是個有規則的javascript函數,它就象一個容器(定義參數,調用其他函數等等).它們兩者所不同的是構造器函數是由 new 操作符調用的.(你將在下面的例子中看到).基於函數語法形式的對象定義,我們可以使它工作得最好.
讓我們用現實世界中的貓來舉個例子.貓的 name 和 color 是貓的屬性.meeyow(貓叫)是它的一個方法.重要的是任何不同的貓都可能有不同的 name 和 meeyow 的叫聲.為了建立適應這些特征的對象類,我們將使用對象構造器. 復制代碼 代碼如下:<script language="javascript" type="text/javascript"> <!--
function cat(name) { this.name = name; this.talk = function() { alert( this.name + " say meeow!" ) } }
cat1 = new cat("felix") cat1.talk() //alerts "felix says meeow!"
cat2 = new cat("ginger") cat2.talk() //alerts "ginger says meeow!"
firstCat = new cat("pursur") firstCat.changeName("Bill") firstCat.talk() //alerts "Bill says meeow!"
//--> </script>
就象你所看到的.我們僅只用了 關鍵字 prototype 實現了在對象定義後馬上增加了changeName方法.這個方法被所有的實例共享. 用原型(prototype) 重載 javascript 對象 原型 在自定義對象和有選擇性的重載對象上都可以工作.比如 Date() 或 String 這可能是無止境的. 子類和超類 在JAVA 和C++裡,有關於類層次的外在概念.每一個類能有一個角色. In Java and C++, there is an explicit concept of the class hierarchy. i.e. Every class can have a super class from which it inherits properties and methods. Any class can be extended, or sub-classed so the resulting subclass can inherit its parent's behavior. As we have seen, javascript supports prototype inheritance instead of class based. It's possible for inheritance to happen other ways, however.
The following is an example of inheritance through functions.
// These are the same object.property object["property"]
//--> </script>
<SCRIPT LANGUAGE="javascript"> <!-- function Circle (xPoint, yPoint, radius) { this.x = xPoint; this.y = yPoint; this.r = radius; }
var aCircle = new Circle(5, 11, 99); alert(aCircle.x); alert(aCircle["x"]); //--> </SCRIPT> How do I loop through properties in an object? You need to use a for/in loop. 我們可以通過for in循環來遍歷對象的屬性。
var testObj = { prop1 : "hello", prop2 : "hello2", prop3 : new Array("hello",1,2) } for(x in testObj) alert( x + "-" + testObj[ x ] ) //--> </script> <SCRIPT LANGUAGE="javascript"> <!-- var Circle = { x : 0, y : 1, radius: 2 } // another example
for(p in Circle) alert( p + "-" + Circle[ p ] ) //--> </SCRIPT>
The important thing to notice is that in the object syntax the property is an identifier, whereas in the array syntax, it's a string. The obvious benefits of using an array syntax to access an object is because of the literal data type, you can easily concat strings and play around with them to access an object. For this to work with the standard syntax, an eval() would need to be used. 應該值得注意的是對象的屬性只是一個標識字符,盡管在一個數組裡是一個字符串,因為是一個literal的數據類型,所以有利於使用數組的方式的操作一個對象。你也可以很容易的存取一個對象在標准的語句中。這個時候eval()函數可能用得到。 <script language="javascript" type="text/javascript"> <!--