对象
什么是对象
对象是javascript中的一种数据类型;
对象是一种复合型数据类型,可以将很多个数据放在一个单元中;
对象通过属性来获取相应的数据;
对象通过方法来实现数据的处理和功能;
对象是一个无序的数据的集合。
直接创建再定义对象
var student_01 = new Object();
student_01.name = "都根"; //属性定义
student_01.home = "佳佳布鲁根";
student_01.age = 23;
student_01.weight = "70kg";
直接创建自定义对象虽然方便直观,但是要创建多个类型相同的对象就很繁琐。
定义一个构造函数,就可以通过这个自定义函数创建自定义对象。与普通的函数不同,调用构造函数必须使用new运算符
构造函数定义
1.定义构造函数
function 构造函数名(参数){
//函数的属性与方法;
}
2.通过构造函数来创造
var 对象名 = new 构造函数名
this 语句
在一个对象内部,this指当前的对象本身。
使用自定义构造函数创建
function Student(name,age,id){//定义构造函数
this.name=name //定义构造函数的属性
this.age=age;
this.id=id;
}
var student01=new Student("李狗蛋",21,"110104");
var student01=new Student("张全蛋",20,"110105");
var student01=new Student("王二蛋",24,"110106");
对象属性的枚举
一个对象通常有多个属性,如果要获取某个属性值,就必须用“对象名.属性名”来获取。
可以通过for。。。in语句来实现对象属性的枚举。
function Student(name,age,id){//定义构造函数
this.name=name //定义构造函数的属性
this.age=age;
this.id=id;
}
var student01=new Student("李狗蛋",21,"110104");
for(var prop in student01){
console.log("属性名:"+prop+"属性值为:"+student01[prop])
}
删除对象
delete对象名.属性
//删除一个对象的属性
function Student(name,age,id){
this.name=name;
this age=age;
this id=id;
}
var student01=new Student("李狗蛋",21,"110104");
delete student01.id;
console.log(student01.id);//已经删除的对象返回值为undefined
创建有默认值的构造函数
function Student(name,id,sex){
this.name=name;
this.id=id;
if(sex==undefined){
this.sex="boy";
}
else{
this.sex=sex;
}
}
var student1=new Student("李狗蛋","110102")
var student2=new Student("王钢蛋","110104","girl")
创建有方法的构造函数
方法:一个对象内,能够实现一定功能的函数。
与属性一样,也需要使用this运算符来初始化对象的方法
function Student(name,id,sex){
this.name=name;
this.id=id;
this.sayName=function(){
console.log(this.name);
}
}
var student01 = Student("李狗蛋","110234");
构造函数
function Cat(name,sex,age){
this.name=name;
this.leg=4;
this.sex=sex;
this.age=age;
this.sayName=function(){
console.log(this.name);
}
}
var dahuang=new Cat("dahuang","boy",8);
var xiaobai=new Cat("xiaobai","boy",8);
var yangrouchuan=new Cat("yangrouchuan","boy",8);
构造函数在内存中对象的存储
huahua:name,sex,age
原型对象
Js所有的函数都有一个prototype属性,这个属性引用了一个对象,即原型对象,也简称原型。
语法
构造函数名.prototype
定义原型对象属性
构造函数名.prototype.属性名
function Cat(name,sex,age){
this.name=name;
this.sex=sex;
this.age=age;
}
Cat.prototype.leg=4;
Cat.prototype.sayName=function(){
console.log(this.name);
}
var dahuang = new Cat("dahuang","boy",8);
console.log(dahuang.leg);
dahuang.sayName();
字符串的原型对象:String.prototype
数组的原型对象:Array.prototype
类
面向对象的程序开发中都有一个类的概念,专指一组有共性的对象的属性的描述。
如,可以把所有的狗都定义为一个类,猫定义为一个类。
javascript中没有支持真正的类的定义
但是在javascript中可以定义伪类,实现的方法就是通过构造函数和原型对象。
所以我们可以说javascript中的类=构造函数和原型对象
类的继承
定义一个动物的类,再定义一个猫科动物的类,并且让猫科动物的类继承动物类的方法。
function Animal(){
Animal.prototype.sayName=function(){
console.log(this.name);
}
}
function Cat(name,leg,say){
this.name=name;
this.leg=leg;
this.say=say;
}
Cat.prototype=new Animal();
var dahuang=new Cat("dahuang",8,"miaomiao");
console.log(dahuang.leg);
dahuang.sayName();