<!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>
上述运行结果: