多的不说,直接上练习例子:
1.对象的属性、创建、构造函数、方法
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type="text/javascript">
//函数:用作对象的方法
function Rectangle_area() {return this.width * this.height;}
function Rectangle_perimeter() {return this.width * 2 + this.height * 2;}
function Rectangle_set_size(w, h) { this.width = w; this.height = h;}
//object_Rectangle 的构造函数
function object_Rectangle(w, h)
{
//初始化对象的属性
this.width = w;
this.height = h;
//定义对象的方法
this.area = Rectangle_area;
this.perimeter = Rectangle_perimeter;
this.set_size = Rectangle_set_size;
}
//创建object_Rectangle对象,调用它的方法
var r = new object_Rectangle(3, 4);
var a = r.area();
document.write(a);
</script>
</body>
</html>
结果: 12
2.原型对象和继承
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type="text/javascript">
//函数:用作对象的方法
function Rectangle_area() {return this.width * this.height;}
function Rectangle_perimeter() {return this.width * 2 + this.height * 2;}
function Rectangle_set_size(w, h) { this.width = w; this.height = h;}
//object_Rectangle 的构造函数
function object_Rectangle(w, h)
{
//初始化对象的属性
this.width = w;
this.height = h;
//定义对象的方法
this.area = Rectangle_area;
this.perimeter = Rectangle_perimeter;
this.set_size = Rectangle_set_size;
}
//创建原型对象
new object_Rectangle(0,0);
//定义一个常量: 所有<span style="font-family: Arial, Helvetica, sans-serif;">object_Rectangle对象共有的属性</span>
object_Rectangle.prototype.d = 5;
object_Rectangle.prototype.return = function () { return this.width * this.d;}
//创建object_Rectangle对象,调用它的方法
var r = new object_Rectangle(3,4);
var a = r.area();
var b = r.return();
document.write(a + " " + b);
var name = "";
</script>
</body>
</html>
结果:12 15
3.作为关联数组的对象
object.property 等价于 object[ "property" ]
二者存在区别:
前者是静态访问,“.”访问的是标识符,不是任何类型,程序无法操作它;
后者可以动态访问:
eg:
var address= "";
for(var i = 0, i <4, i++){
address += object_Rectangle["address" + i] + "\n";
}
读取属性
address0,address1,address2,address3