javascript对象学习笔记

多的不说,直接上练习例子:

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值