创建一个电脑对象,有颜色,有重量,有品牌,有型号,可以看电影,可以听音乐,可以打游戏,可以敲代码
1.使用系统自带的构造函数创建对象;
//(1)创建对象
var computer = new Object();
//(2)为对象添加属性
computer.color = '黑色';
computer.weight = '4kg';
computer.brand = 'mac';
computer.type = 'MacBook Pro';
//(3)为对象添加方法
computer.movie = function(){
console.log('我可以看电影;');
}
computer.music = function(){
console.log('我可以t听音乐;');
}
computer.play = function(){
console.log('我可以打游戏;');
}
computer.code = function(){
console.log('我可以敲代码;');
}
//(4)对象方法的调用
computer.movie();
computer.music();
computer.play();
computer.code();
//(5)对象属性的调用
console.log(computer.color);
console.log(computer.weight);
console.log(computer.brand);
console.log(computer.type);
2.自定义构造函数创建对象
(1)定义一个构造函数
function Computer(color,weight,brand,type){
this.color = color;
this.weight = weight;
this.brand= brand;
this.type = type;
this.movie = function(){
document.write('这台'+this.color+',重量为'+this.weight+'的'+this.type+'电脑可以看电影<br>');
},
this.game = function(){
document.write('这台'+this.color+',重量为'+this.weight+'的'+this.type+'可以打游戏<br>');
},
this.code = function(){
document.write('这台'+this.color+',重量为'+this.weight+'的'+this.type+'可以敲代码<br>');
}
}
(2)创建对象
var comp = new Computer('红色','4kg','华硕','华硕的类型');
(3)调用函数
comp.movie();
comp.game();
comp.code ();
3.字面量形式创建对象
(1)创建对象
var computer2 = {
color:'白色',
weight:'5kg',
brand:'戴尔',
type:'e480',
movie: function (){
document.write('这台'+this.color+',重量为'+this.weight+'的'+this.type+'电脑可以看电影<br>');
},
game: function (){
document.write('这台'+this.color+',重量为'+this.weight+'的'+this.type+'可以打游戏<br>');
},
write: function (){
document.write('这台'+this.color+',重量为'+this.weight+'的'+this.type+'可以敲代码<br>');
}
}
(2) //调用对象的函数
computer2.movie();
computer2.game();
computer2.write();