对象的增删改查,实例化对象

一、对象的增删改查
添加属性 对象.属性名 = 属性值;
查询 对象.属性名
console.log(obj.age);
修改 对象.属性名 = 新属性值
删除 delete 对象.属性名
var teacher = {
name:‘张三’,
age: 32,
sex:‘男’,
weight: 145,
weight: 130,
teach: function(){
console.log(‘I am teaching JavaScript’);
},
smoke: function(){
console.log(‘I am smoking’);
},
eat: function(){
console.log(‘I am having a dinner’);
}
}
teacher.address = ‘北京’;
teacher.drink = function(){
console.log(‘I am drinking beer’);
}
teacher.eat();
console.log(teacher);
delete teacher.address;
delete teacher.smoke;

二、实例化对象

this对象的本身。
var teacher = {
name: ‘张三’,
say:function(){
console.log(this.name)
}
}

// var obj = {
// name: ‘张三’,
// sex : ‘male’
// }
// obj.name = ‘李四’;
//对象字面量,对象直接量
//构造函数
//系统自带的构造函数

// var obj = new Object();//和对象字面量相等
// obj.name = '张三';
// obj.sex = '男士';
// console.log(obj);
//对象是通过构造函数创建的对象实例

function Teacher(){
this.name = ‘张三’;
this.sex = ‘男士’;
this.smoke = function(){
console.log(‘I am smoking’);
}
}//构造函数,构造工厂
var teacher1 = new Teacher();//实例化的对象
var teacher2 = new Teacher();
teacher1.name = ‘李四’;
console.log(teacher1,teacher2);

function Teacher(){
this.name = ‘张三’;
this.sex = ‘男士’;
this.weight = 130;
this.smoke = function(){
this.weight–;
console.log(this.weight);
}
this.eat = function(){
this.weight++;
console.log(this.weight);
}
}
var t1 = new Teacher();
var t2 = new Teacher();
t1.smoke();
t1.smoke();
console.log(t2.weight);

function Teacher(name,sex,weight,course){
this.name = name;
this.sex = sex;
this.weight = weight;
this.course = course;
this.smoke = function(){
this.weight–;
console.log(this.weight);
}
this.eat = function(){
this.weight++;
console.log(this.weight);
}
}
var t1 = new Teacher(‘张三’,‘男’, 145, ‘JavaScript’);
var t2 = new Teacher(‘李四’, ‘女’, 90, ‘HTML’);
t1.smoke();
t1.smoke();
console.log(t1);
console.log(t2);

function Teacher(opt){
this.name = opt.name;
this.sex = opt.sex;
this.weight = opt.weight;
this.course = opt.course;
this.smoke = function(){
this.weight–;
console.log(this.weight);
}
this.eat = function(){
this.weight++;
console.log(this.weight);
}
}
var t1 = new Teacher({
name:‘张三’,
sex:‘男’,
weight: 145,
course:‘JavaScript’
});
var t2 = new Teacher({
name:‘李四’,
sex:‘女’,
weight: 90,
course:‘HTML’
});
console.log(t1);
console.log(t2);

var attendence = {
students: [],
total: 6,
join: function(name){
this.students.push(name);
if(this.students.length === this.total){
console.log(name + ‘到课,学生已到齐’);
}else{
console.log(name + ‘到课,学生未到齐’);
}
},
leave: function(name){
var idx = this.students.indexOf(name);
if(idx !== -1){
this.students.splice(idx,1);
}
console.log(name + ‘早退’);
console.log(this.students);
},
classOver: function(){
this.students = [];
console.log(‘已下课’);
}
}
attendence.join(‘张三’);
attendence.join(‘李四’);
attendence.join(‘王五’);
attendence.join(‘赵六’);
attendence.join(‘吴七’);
attendence.join(‘孙八’);
attendence.leave(‘李四’);
attendence.classOver();

猜你喜欢

转载自blog.csdn.net/weixin_37150764/article/details/109083160