任务一:利用字面量创建对象
任务要求: 创建一个商品对象goods,并设置3个属性,分别为name、price和number,定义一个方法show(),该方法用于输出商品信息。
任务实现:
<script>
var goods = { //创建goods对象
name: "无线鼠标",
price: 166,
number: 3,
show: function () {
alert("商品名称:" + this.name + "\n商品单价:" + this.price + "\n商品数量:" +this.number
); //输出商品信息
}
}
goods.show();
</script>
任务二:利用构造函数创建对象
任务要求:首先定义一个Student()构造函数,然后利用Student()构造函数创建学生对象,实现自我介绍。
任务实现:
<script>
//定义一个Student()构造函数
function Student(name, age) {
this.name = name;
this.age = age;
this.introduce = function () {
console.log('大家好,我叫' + this.name + ',今年' + this.age + '岁');
};
}
//使用Student()构造函数创建对象
var stu1 = new Student('小明', 18);
stu1.introduce();
var stu2 = new Student('小强', 19);
stu2.introduce();
var stu3 = new Student('小红', 18);
stu3.introduce();
</script>
任务三:静态成员和实例成员的区别
任务要求:练习静态成员和实例成员的区别
任务实现:
<script>
function Person(name) {
//添加实例成员
this.name = name;
this.say = function () {
console.log('hello');
};
}
//添加静态成员
Person.class = "102班";
Person.run = function () {
console.log('run');
};
//使用静态成员
console.log(Person.class); //输出结果:102班
Person.run(); //输出结果:run
//使用实例成员
var p1 = new Person('小明');
console.log((p1.name)); //输出结果:小明
p1.say(); //输出结果:Hello
</script>