看了几个小时原型,复习了一下,在想这个prototype这个在实际项目的运用,到底怎么用。
jquery里面是有一大堆这个玩意儿的,但已经是封装好的东西,再说也不是自己的东西。
于是,自己查了些资源,搞了个这个东西,也许以后会用上,也许不会用上,就当只是巩固了
情景再现:一条鱼只有两条属性
function Fish(name,color){
this.name=name;
this.color=color;
}
鱼妈妈生了3条鱼宝宝啦
var fish1=new Fish("小苏","red");
var fish2=new Fish("小东","green");
var fish3=new Fish("小豪","write");
就这样,鱼儿们快乐的生活的20年,
有一天,东海龙王说:你们现在都要上户口,现在年龄多大呀,家住哪里啊,都要登记,重要的事说一遍够不够
这个时候就假装它们是一个模子刻出来的
Fish.prototype.age="20";
Fish.prototype.where="成都";
东海龙王数据库一查,该有的内容都要了,信息采集
html
<table border="" cellspacing="0" cellpadding="">
<tr><th>姓名</th><th>颜色</th><th>年龄</th><th>住址</th></tr>
</table>
js
var jshtml='';
for(var i=1;i<=3;i++){
var fish=eval("fish"+i);
jshtml+=`<tr><td>`+fish.name+`</td><td>`+fish.color+`</td><td>`+fish.age+`</td><td>`+fish.where+`</td></tr>`;
console.log(fish.name+" "+fish.color+" "+fish.age+" "+fish.where);
}
$("table").append(jshtml);
页面效果
console.log
那么问题来了,嫁出去的鱼,生的小鱼儿,年龄才3岁,在北京出生,怎么上户口呢
追加:年龄3岁,北京出生的新生儿怎么上户口
prototype原型链上可以定义属性,也可以定义方法
之前的基础上,原型链上只增加了一个方法
html
<table border="" cellspacing="0" cellpadding="">
<tr><th>姓名</th><th>颜色</th><th>年龄</th><th>住址</th></tr>
</table>
js
function Fish(name,color){
this.name=name;
this.color=color;
}
var fish1=new Fish("小苏","red");
var fish2=new Fish("小东","green");
var fish3=new Fish("小豪","write");
Fish.prototype.age="20";
Fish.prototype.where="成都";
Fish.prototype.addfish=function(name,color,age,where){
this.name=name;
this.color=color;
this.age=age;
this.where=where;
}
var fish4=new Fish();
fish4.addfish("小鱼儿来了","pink",3,"北京")
var jshtml='';
for(var i=1;i<=4;i++){ //有4个鱼宝宝了,循环4次
var fish=eval("fish"+i);
jshtml+=`<tr><td>`+fish.name+`</td><td>`+fish.color+`</td><td>`+fish.age+`</td><td>`+fish.where+`</td></tr>`;
console.log(fish.name+" "+fish.color+" "+fish.age+" "+fish.where);
}
$("table").append(jshtml);
