对象是js里的一个重要概念,创建对象一共有七种方法,常用的有五种
(1.)
直接创建法
var temp=new Object();//注意Object的O是大写的
temp.name="li";
temp.mobile="#############";
temp.study=function(name){
console.log(name+"正在学习");
}
temp.play=function(){
console.log("去玩了");
}
temp.study(temp.name);//调用对象里面的方法
temp.play();//调用对象里面的方法
console.log(temp.mobile);//调用对象里的属性
console.log(temp["mobile"]);//另外一种对用对象属性的方式
(2.)
初始化法
var student={
name:"li",
age:19,
addr:"保密",
study:function(name)
{
console.log(name+"正在学习");
}
}
student.study(student.name);//调用对象里的方法
console.log(student.age);//调用对象里的属性
在这说下this的用法
//下面体会下this.
console.log("!!!!!!!!!!!!!!!!!!!!!!!!");
var student={
name:"li",
age:19,
addr:"保密",
study:function()
{
console.log(this.name+"正在学习");//注意跟上面不一样.神奇的this.其实用student代替this一样可以,因为this就是代替对象名
}
}
student.study();//调用对象里的方法
console.log(student.age);//调用对象里的属性
(3.)
原型式
//3.原型式。构造函数跟对象方法分开了,但是却不方便赋值。注意构造函数名首字母大写
function Student(){
}//这个跟普通的定义方法不一样,这个是构造方法,首字母大写
Student.prototype.name="hiahia";
Student.prototype.age=12;
Student.prototype.dohomework=function()
{
console.log(this.name+"正在做作业");
}//截止到这里声明完成
var student=new Student();//这里创建对象,叫student
student.dohomework();//调用
//Student.prototype.dohomework();这样也是可以调用的
(4.)
构造函数式
//4.构造函数式,便于对属性赋值,但是对象的方法跟构造函数混在一起
function Student(name,age){
this.name=name;
this.age=age;
this.study=function()
{
console.log(this.name+"正在学习");
}
}//到此声明完成
var student=new Student("li",12);//创建对象,并传入参数。
student.study();
console.log(student.age);
(5.)
混合式-构造函数式与原型式的结合
//5.混合式
function Teacher(name,age){
this.name=name;
this.age=age;
}
Teacher.prototype.teach=function()
{
console.log(this.name+"正在上课");
}//声明结束
var teacher=new Teacher("老师",30);//创建对象
teacher.teach();
console.log(teacher.age);
混合式具有两种方式的优点