练习1:通过Object创建对象,该对象包含bookid、bookend、publish三个属性
包含的方法有:
setBookName(name):修改bookName属性值
setPublish(publish):修改publishing属性值
showBookInfo():显示图书信息
let obj = new Object();
obj.bookId = '202011';
obj.bookName = '三国演义';
obj.publishing = '商务印书馆';
obj.setBookName = function (name) {
this.bookName = name; //this代表当前对象obj
}
obj.setPublishing = function (publishing) {
this.publishing = publishing;
}
obj.showBookInfo = function () {
console.log('图书编号:', this.bookId);
console.log('图书名称:', this.bookName);
console.log('出版社:', this.publishing);
}
obj.showBookInfo();
console.log('------------------------------');
obj.setBookName('水浒传');
obj.setPublishing('机械工业出版社');
obj.showBookInfo();
/* ------------------------------------------------------------*/
let book = new Object({
bookId: '001',
bookName: 'ABC',
publishing: '电子工业',
setBookName:function(name){
this.bookName = name
},
setPublishing:function(publishing){
this.publishing = publishing
},
showBookInfo:function(){
let str = `图书编号:${this.bookId}\n图书名称:${this.bookName}\n出版社:${this.publishing}`
console.log(str)
}
})
book.showBookInfo()
console.log('--------------------------')
book.setBookName('红楼梦')
book.setPublishing('北大出版社')
book.showBookInfo()
练习3、定义一个构造方法Car(),属性是:color、engine、type ,方法是:setColor(color)、setEngine(engine)、setType(type)、showCar()
创建两个对象,分别是car1和car2,显示car1的信息,修改car2的三个属性并显示出来
//1.定义构造方法:Car()
function Car(color,engine,type){
this.color = color
this.engine = engine
this.type = type
this.setColor = function(color){
this.color = color
}
this.setEngine = function(engine){
this.engine = engine
}
this.setType = function(type){
this.type = type
}
this.showCar = function(){
console.log('颜色:',this.color)
console.log('引擎:',this.engine)
console.log('型号:',this.type)
}
}
//2.创建对象car1:是构造方法实例化。对象就是实例
let car1 = new Car('红色','L4','2.0')
car1.showCar()
console.log('----------------------------')
//3.创建对象car2:
let car2 = new Car('蓝色','v6','3.0')
car2.showCar()
练习4:定义构造方法Person(name,age),属性有:name,age,方法有:setName(name),setAge(age),display()
使用该构造方法创建两个对象:
第一个对象的name:郭靖,age = 22
第二个对象的name:黄蓉,age = 18
显示这两个对象信息
function Person(name,age) {
this.name = name,
this.age = age,
this.setName = function (name) {
this.name = name;
},
this.setAge = function (age) {
this.age = age;
}
this.display = function() {
console.log('姓名:',this.name);
console.log('年龄:',this.age);
}
}
let p1 = new Person('郭靖','22');
// p1.setName = '郭靖';
// p1.setAge = '18';
p1.display()
let p2 = new Person('黄蓉','18');
p2.display()