js中的继承
function CreateAnimal(name,age){
this.name = name;
this.age = age;
CreateAnimal.prototype.hobby = '唱歌';
this.sayHi = function(){
alert('heelo')
}
}
function CreateDog(name,age,gender){
//name,age都继承自父类
CreateAnimal.apply(this,[name,age]);
this.gender = gender;
this.eatFood = function(){
alert('jjjj')
}
}
var dog = new CreateDog('zhang',34,'nam')
console.log(dog1.name);
console.log(dog1.age);
console.log(dog1.proto.hobby);//空,不会继承原型里的东西
要想继承原型里存放的东西,可以用原型链实现继承
console.log(CreateDog.prototype);//指向的就是CreateDog
原型链实现继承:
原理是差不多的,就是改变子类原型的指针指向,
var animal = new CreateAnimal('阿黄', 8);
// 让父类的对象充当子类的原型
CreateDog.prototype = animal;
CreateDog.prototype.constructor = CreateDog;
利用原型链简化代码
比如求和:
var arr = [1,2,3,4,5]
Object.prototype.sum = function(){
var sum = 0;
for(var i = 0;i<this.length;i++){
sum = sum+parseInt(this[i]);
}
return sum;
}
console.log(arr.sum())即可得出结果
此时就很方便,不管你要求谁的和,只要调用这个就行
var see = ‘233434435’
console.log(see.sum())即可