JavaScript高级程序设计(第2版) 学习笔记:(三)js原型的四种形态

第一种形态

当声明一个函数时,它就出现第一种形态

函数声明,如下:


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原型中

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值