在构造函数中为了避免创建多个对象,造成方法的重复创建,我们一般在原型对象上创建方法
如
Student.prototype.method=function(){
console.log(123);
}
但这种方法仅适用于对象的方法较少时,如果对象方法有很多,就需要不断重复
类似Student.prototype.method=function.....
这样也很麻烦
我们可以通过类似于对象字面量的方式
如
Stuent.prototype = {
sum:function(){
....
},
scort:function(){
....
}
}
但使用这种方式也有要注意的地方,这里我们实际上重写了prototype
对象,我们知道prototype
有一个constructor
属性,这个属性是指向当前对象的构造函数但这种方式会重写了prototype
所以我们要为prototype
加上constructor:Student
手动指向构造函数。
Stuent.prototype = {
constructor:Student,
sum:function(){
....
},
scort:function(){
....
}
}
我们还可以利用原型对象为内置对象添加方法
如下 为数组对象添加一个偶数求和方法
Array.prototype.getSum = function(){
var sum = 0;
for(var i = 0;i<this.length;i++){
if(this[i] % 2 ===0){
sum+=this[i]
}
}
return sum
}
var arr = [1,2,3,4];
console.log(arr.getSum());
//结果输出6
但是为内置对象添加方法不允许下面这种操作
Array.prototype.getSum={
getSum:function(){}......
}