对象字面量,对象直接量
<script>
var teacher = {
name: '张三',
age: 32,
sex: 'male',
height:176,
weight:130,
teach:function(){
console.log('I am teaching Javascript');
},
eat:function(){
console.log('I am having a dinner');
}
}
console.log(teacher.name);
teacher.eat();
// 增加属性
teacher.address = '北京';
// 增加方法
teacher.drink = function(){
console.log('I am drink beer');
}
// 修改属性
teacher.height = 180;
// 修改方法
teacher.teach = function(){
console.log('I am teaing HTML');
}
// 删除属性
delete teacher.address;
// 删除方法
delete teacher.teach;
</script>
<script>
var teacher = {
name: '张三',
age: 32,
sex: 'male',
height:176,
weight:130,
teach:function(){
console.log('I am teaching Javascript');
},
eat:function(){
this.weight++;
console.log(this.weight)
},
smoke:function(){
this.weight--;
console.log(this.weight)
}
}
teacher.smoke();
teacher.eat();
</script>
方法内部传参数,执行函数方法传入实参
<script>
var attendance = {
students:[],
total:6,
join:function(name){
if(this.students.push(name) == this.total){
console.log(name + '到课,学生未到齐');
}else{
console.log(name + '到课,学生到齐');
}
console.log(this.students);
},
leave:function(name){
var idx = this.students.indexOf(name);
if( idx!== -1){
this.students.splice(idx,1);
}
console.log(name +'早退');
},
classover:function(){
this.students = [];
console.log('已下课');
}
}
attendance.join('张三');
attendance.join('李四');
attendance.join('王五');
attendance.join('牛二');
attendance.join('王五');
attendance.join('王五');
attendance.leave('张三');
</script>
构造函数
系统内自带的构造函数
<script type="text/javascript">
var obj = new Object();
obj.name = '张三';
obj.sex = '男士';
console.log(obj);
</script>
自定义构造函数
<script type="text/javascript">
// 自定义构造函数
// 大驼峰
function Teacher(){
this.name = '张三';
this.sex = '男士';
this.smoke = function(){
console.log('I am smoking');
}
}
var teacher = new Teacher();
</script>
this的指向,当实例化的时候才指向这个对象
另一种构造函数方法
<script type="text/javascript">
function Teacher(name,sex,weight){
this.name = name;
this.sex = sex;
this.weight = weight;
this.smoke = function(){
this.weight--;
console.log(this.weight);
}
this.eat = function(){
this.weight++;
console.log(this.weight);
}
}
var teacher1 = new Teacher('张三','男',145);
var teacher2 = new Teacher('李四','女',100);
</script>
方法3
<script type="text/javascript">
function Teacher(opt){
this.name = opt.name;
this.sex = opt.sex;
this.weight = opt.weight;
this.smoke = function(){
this.weight--;
console.log(this.weight);
}
this.eat = function(){
this.weight++;
console.log(this.weight);
}
}
var teacher1 = new Teacher({
name:'张三',
sex:'男',
weight:145
});
var teacher2 = new Teacher({
name:'李四',
sex:'女',
weight:100
});
</script>