自定义对象的三种方式
一、使用Object
// 1.创建对象 var stu=new Object(); // 2.为对象添加属性(特征) stu.name='tom'; stu.age='27'; // 3.为对象添加方法(行为) stu.drink=function(){ console.log('我是李浩阳,正在喝热美式。。。'); } stu.rush=function(){ console.log('我是闫博,今天下午我只吃水果捞。。。'); } stu.show=function(){ console.log('w我叫'+stu.name+',年龄:'+this.age); } //4.调用对象的属性和方法 console.log(stu.name,stu['name']); console.log(stu.age,stu['age']); stu.drink(); stu.rush();
二、使用构造函数
用来创建对象的函数,称为构造函数或构造器,相当于自定义了一个类型
function 构造函数名(形参1,形参2...){//为了区别于普通函数,构造函数名建议首字母大写 this.属性名=形参1; this.属性名=形参2; this.方法名=function(){ 方法体 }; } var 对象名=new 构造函数名(实参1,实参2...);
示例:
// 1.定义一个构造函数,用来创建对象 function Student(){ // 对象的属性 this.name='tom'; this.age='18'; // 对象的方法 this.study=function(){ console.log('正在学习。。。'); } } // 2.调用构造函数,来创建对象 var stu=new Student(); console.log(stu.name,stu['name']); stu.study();
// 带参 // 1.定义一个构造函数(带参),用来创建对象 function Student(name,age){ // 对象的属性 this.name=name; //此处的this表示将来创建的对象 this.age=age; // 对象的方法 this.study=function(){ console.log('正在学习。。。'); } this.study=function(){ console.log('跑步。。。'); } this.show=function(){ console.log('我叫'+this.name+',年龄:'+this.age); } } // 2.调用构造函数,来创建对象 var stu1=new Student('tom',18); console.log(stu1.name,stu1.age); var stu2=new Student('alice',20); console.log(stu2.name,stu2.age); stu1.show(); stu2.show();
三、使用对象字面量的方式创建对象
多个属性之间以逗号隔开,属性名和属性值之间以冒号隔开 var 对象={ 属性名:属性值, 属性名:属性值, 方法名:function(){ 方法体 } };
示例:
/* 字面量 */ var str='hello world'; //字符串字面量 var array=[12,4,23,67]; //数组字面量 var fn=function(){ //函数字面量 console.log(111); } /* 对象字面量 */ var stu={ name:'tom', age:18, 'eaxm-score':99, //特殊属性名必须用单引号引起来 study:function(){ console.log('正在学习。。。'); }, run:function(){ console.log('正在跑步'); }, show:function(){ console.log('我叫'+this.name+',年龄:'+this.age); } } console.log(stu.age,stu.name,['eaxm-score']); stu.study(); stu.show();