js创建对象的三种方式

创建一个电脑对象,有颜色,有重量,有品牌,有型号,可以看电影,可以听音乐,可以打游戏,可以敲代码
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();
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值