102-(面向对象)原型+构造函数

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>原型</title>
</head>
<body>
	
	<script>
		// 当我们创建一个函数(对象), 都会有一个 prototype 属性,这个属性是一个小对象, 也称作原型对象,
		// 其里面包含特定类型的所有实例对象共享的属性和方法.
		//
		// 通过这个函数创建出来的实例对象,都能够共享这个原型对象下的方法和属性, 
		// 所以我们只需要把想要共享的东西放在函数的 prototype属性下, 不想共享的通过构造函数来创建即可
		

		var arr1 = new Array(1, 2, 'ax', 3, 4); // arr1.push
		var arr2 = new Array(5, 6, 7, 8); // arr2.push()

		Array.prototype.sum = function() {
			// this  
			var result = 0;
			for(var i =0; i < this.length; i++) {
				if((typeof this[i]) === 'number') {
					result += this[i]	
				}
				// result += this[i]	
			}
			return result;
		}
		console.log(arr1);
		console.log(arr1.sum());


		function Box(width, height) {
			this.width = width;
			this.height = height;
		}
		Box.prototype.name = "盒模型";
		Box.prototype.getArea = function() {
			return this.width * this.height;
		}

		var box1 = new Box(3, 4);
		console.log('box1',box1);
		//调用prototype属性的时候,.prototype必须省略
		console.log(box1.getArea());

		var box2 = new Box(3, 4);
		console.log(box2.getArea());
		console.log('box2',box2);
		

		//box1和box2是两个不同的被实例化的对象
		console.log('box1 == box2',box1 == box2);// false
		console.log('box1 === box2',box1 === box2);// false
		console.log(box1.prototype === box2.prototype); // true

	</script>
</body>
</html>

上述运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七色的天空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值