JavaScript中的原型链举例说明

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小节)

猜你喜欢

转载自blog.csdn.net/qq_34538534/article/details/82859471