JavaScript中的原型链举例说明

本文深入解析JavaScript中的原型链概念,包括对象的原型属性、构造器、原型链的创建及使用,通过具体示例展示了如何利用原型链实现对象的继承。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JavaScript中关于原型链的概念十分重要。原型链,即实例对象与其原型间的关系链。

首先,要理解什么是对象的原型?如何创建对象的原型?

每个对象都有预设的默认属性prototype,其中包含两个属性constructor和_proto_,其中constructor为该对象的类型,一般情况下为函数构造器,_proto_即可理解为该对象的原型,为Object(构造器).prototype。请看举例:

function Foo(){}
Foo.prototype.a=1;
console.log(Foo.constructor);
console.log(Foo.prototype);

 

 使用new关键字创建的对象x,其原型为创建的构造器类型,继承原构造器的prototype上的属性a:

var x=new Foo();
console.log(x.constructor);
console.log(x.a);

 

创建对对象原型可用new关键字,还可使用Object.creat方法创建,请看举例:

function Person(name,age){
	this.name=name;
	this.age=age;
	}
	Person.prototype.LEGS_NUM=2;
	Person.prototype.ARMS_NUM=2;
	Person.prototype.hi=function(){
		  console.log(this.name+" is saying hi to you.");
		}
	Person.prototype.walk=function(){
		  console.log(this.name+" is walking.");
		}
	
function Student(name,age,className){
	  Person.call(this,name,age);
	  this.className=className;
	  }
	  
	  Student.prototype=Object.create(Person.prototype);
	  Student.prototype.constructor=Student;
	  
	  Student.prototype.hi=function(){
		    console.log("Student "+this.name+" is saying hi to you.");
		  }
	  Student.prototype.learn=function(a){
		    console.log("Student "+this.name+" is learning "+a+" hardly.");
		  }
	
var Cindy=new Student("Cindy",22,"Lighting");
console.log(Cindy.LEGS_NUM);
console.log(Cindy.ARMS_NUM);
Cindy.learn("Programming");
Cindy.hi();
Cindy.walk();

var Lynn=new Person("Lynn",22);
Lynn.hi();
Lynn.walk();

 

 其中Student.prototype=Object.create(Person.prototype);
      Student.prototype.constructor=Student;

即是将Student的_proto_与Person.prototype连接,也就是将Person类型作为Student类型对象的原型,Student类型对象可间接获取Person.prototype上的属性。

这样,为对象创建原型链关系,可便于对象访问原型的Object.prototype上的相关属性。

(以上内容参考慕课网Bosn老师的JavaScript深入浅出第8-1,8-2小节)

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值