对象是javascript中的数据类型之一,是一种复合的数据类型,它将多种数据类型集中在一个数据单元中,并通过对象来存取这些数据的值。
对象实际上就是一些变量和函数的集合。
(1)对象的属性
对象内部的变量称为对象的属性,它是用来描述对象特性的一组数据。
在程序中使用对象的一个属性类似于使用一个工具,就是在属性名前加上对象名和一个句点“."
格式:对象名.属性名
(2)对象的方法
格式:对象民.方法(参数)
方法是作为对象成员的函数,表明对象所具有的行为;而属性是作为对象成员的变量,表明对象的状态。
javascript中可以使用三种对象,即自定义对象、内置对象和浏览器对象。
内置对象是预先编译好的对象,
例如:Math、Date、String、Array、Number、Boolean、Global、Object和RegExp对象等。
浏览器对象,例如:Document、Window对象等
格式:var 对象名={属性名1:属性值1,属性名2:属性值2,属性名3:属性值3……}
var student=
{
name="张三";
sex="男";
age=25;
}
document.write("姓名"+student.name+"<br>");
document.write("性别"+student.sex+"<br>");
document.write("年龄"+student.age);
直接创建自定义对象很方便也很直观,但如果要创建多个相同的对象,要使用这种方法就会很繁琐。
构造函数的函数体内通过this关键字初始化对象的属性和方法。
例如:创建一个学生对象student,可以定义一个名称为Student的构造函数。
function Student(name,sex,age)
{
this.name=name;
this.sex=sex;
this.age=age;
}//this关键字表示对对象自己的属性和方法的引用
var student1=new Student("张三","男",25);
var student2=new Student("李四","女",23);
//创建一个球员对象
如下:
<script>
<h1>梅西</h1>
function Player(height,weight,sport,team,character)
{
this.height=height;
this.weight=weight;
this.sport=sport;
this.team=team;
this.character=character;
}
var player1=new Player("170cm","70kg","football","巴塞罗那","技术出色,意识好");
</script>
构造函数中定义方法
function Student(name,sex,age)
{
this.name=name;
this.sex=sex;
this.age=age;
this.showName=showName;
this.showSex=showSex;
this.showAge=showAge;
}
function showName(){alert(this.name);}
function showSex(){alert(this.sex);}
function showAge(){alert(this.age);}
另外,也可以在构造函数中直接使用表达式来定义函数
function Student(name,sex,age)
{
this.name=name;
this.sex=sex;
this.age=age;
this.showName=function (){alert(this.name);}
this.showSex=function (){alert(this.sex);}
this.showAge=function (){alert(this.age);}
}
----------------------------------------------------------------------------------------------------------
prototype属性是javascript中所有函数都有的属性。该属性可以向对象中添加属性或方法。
语法如下:
object.prototytpe.name=value
如下:
function Circle(r)
{this.r=r;}
Cirecle.prototype.pi=3.14;
Cirecle.prototype.circumference=function()
{
return 2*this.pi*this.r;
}
Cirecle.prototype.area()=function()
{
return this.pi*this.r*this.r;
}
var c=new Circle(10);
document.write("圆的半径为"+c.r+"</br>");
document.write("圆的周长为"+parseInt(c.circumference())+"</br>");
document.write("圆的面积为"+parseInt(c.area()));
Object对象提供了创建自定义对象的简单方式,在使用这种方式是不需要再定义构造函数。
语法:obj=new Object([value])
var student=new Object();
student.name="张三";
student.sex="男";
student.age="25";
student.show=function ()
{
alert("姓名:"+student.name+"\n性别"+student.sex+"\n年龄"+student.age);
}
student.show();
如果在创建Object对象是没有指定参数,javascript将会创建一个Object实例,但该实例并没有具体指定为哪种对象类型,
这种方法多用于创建一个自定义对象。如果在创建Object对象是指定了参数,可以直接将value参数的值转换为相应的对象。
如下代码就是通过Object对象创建了一个字符串对象。
var myObj=new Object("你好javascript!");