一个对象构造器只不过是个有规则的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"> <!--