首页 > 代码库 > javascript—原型
javascript—原型
window.onload = function () {
var arr1 = new Array(1, 2, 3, 4, 5);
var arr2 = new Array(6, 7, 8, 9, 0);
//如果只定义arr1.sum方法arr2.sum不可用
//如果定义原型都可用
//如果定义原型,arr1.sum也定义将执行arr1自己的sum,联想CSS的class和style
//arr1.sum = function () {
// var result = 0;
// for (var i = 0; i < this.length; i++) {
// result += this[i];
// }
// return result+‘test‘;
//};
Array.prototype.sum = function () {
var result = 0;
for (var i = 0; i < this.length; i++) {
result += this[i];
}
return result;
};
alert(arr1.sum());
alert(arr2.sum());
}
javascript—原型