JS中创建自定义对象的方法

1.直接给对象扩充属性和方法;

2.对象字面量;

3.工厂方式;

4.构造函数方式;

5.原型方式;

6.混合方式。

<script>
		// 1.直接给对象扩充属性和方法;
		var cat = {};
		cat.name = '小白';
		cat.color = 'blue';
		cat.food = 'fish';
		cat.skill = function () {
			alert('喵喵~~~');
		}
		cat.skill();
		//2.对象字面量
		var cat2 = {
			name: '小白',
			color: 'blue',
			food: 'fish',
			skill: function () {
				alert('喵喵~~~');
			}
		};
		console.log(cat2.name);
		//3.工厂方式
		function cat4(n, c) {
			var cat = {};
			cat.name = n;
			cat.color = c;
			cat.food = 'fish';
			cat.skill = function () {
				alert('喵喵~~~');
			}
			return cat;
		} 
		var cat5 = cat4('小白','red');
		console.log(cat5.name);
		console.log(cat5.color);
		//4.构造函数方式
		function Cat6(n,c) {
			this.name = n;
			this.color = c;
			this.food = 'fish';
			this.skill = function () {
				alert('喵喵');
			}
		}
		var cat7 = new Cat6('小黄','yellow');
		console.log(cat7.name);
		console.log(cat7.color);
		//5.原型方式
		function Cat8() {};
		Cat8.prototype.name = '小白';
		Cat8.prototype.color = 'white';
		Cat8.prototype.food = 'fish';
		Cat8.prototype.skill = function () {
			alert('喵喵~~~');
		}
		var cat9 = new Cat8();
		console.log(cat9.food);
		//6.构造函数混合方式
		function Cat(n, c) {
			this.name = n;
			this.color = c;
			this.food = 'fish';
		}
		Cat.prototype.skill = function () {
			alert('喵喵hahah~~~');
		}
		var cat10 = new Cat('红','red');
		console.log(cat10.name);
		cat10.skill();
	</script>

  

转载于:https://www.cnblogs.com/handsomehan/p/5882119.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值