第一种形态
当声明一个函数时,它就出现第一种形态
函数声明,如下:
function HelloWorld(name){
this.name=name;
}
形态图如下:
第二种形态
在原型对象中声明方法,代码如下:
HelloWorld.prototype.say=function(){
alert("hello "+this.name);
}
第三种形态
创建2个对象,代码如下:
function HelloWorld(name){
this.name=name;
}
HelloWorld.prototype.say=function(){
alert("hello "+this.name);
}
var hello1=new HelloWorld("张三");
hello1.age=22;
var hello2=new HelloWorld("李四");
hello2.sayWorld=function(){
alert("hello world");
}
alert(hello1.age);//结果: 22
alert(typeof hello2.age);//结果: undefined
hello1.say();//结果:hello 张三
hello2.say();//结果:hello 李四
hello2.sayWorld();//结果: hello world
hello1.sayWorld();//异常信息: hello1.sayWorld is not a function
形态图:
通过形态图,可以看到:
age只有hello1中存在,hello2中并没有
say方法存在原型对象中,由于hello1与hello2是HelloWorld的实例,所以它们都可以访问HelloWorld的原型中的属性与方法
sayWorld只有hello2中存在,hello1中并没有
第四种形态
原型重写,代码如下:
function HelloWorld(name){
this.name=name;
}
HelloWorld.prototype.say=function(){
alert("hello "+this.name);
}
var hello1=new HelloWorld("张三");
//原型重写
HelloWorld.prototype={
sayWorld:function(){
alert("hello world");
}
};
var hello2=new HelloWorld("李四");
hello1.say();//结果:hello 张三
hello2.sayWorld();//结果: hello world
hello1.sayWorld();//异常信息: hello1.sayWorld is not a function
hello2.say();//结果:hello2.say is not a function
形态图:
通过形态图可以看到
say存在于HelloWorld原型中
sayWorld存在于new HelloWorld原型中