首先定义一个对象obj,该对象的原型为obj._proto_,我们可以用es5中的getprototypeof这一方法来查询obj的原型,我们通过判断obj的原型是否与object.prototype相等来证明是否存在obj的原型,答案返回true,所以存在。然后我们定义一个函数foo(),任何一个函数都有它的prototype对象,即函数的原型,我们可以在函数的原型上添加任意属性,之后通过new一个实例化的对象可以共享其属性(下面的两个例子会详细介绍)。
function foo(){}foo.prototype.z = 3;var obj = new foo();obj.x=1;obj.y=2;obj.x //1obj.y //2obj.z //3typeof obj.tostring; //functionobj.valueof(); // foo {x: 1, y: 2, z: 3}obj.hasownproperty('z'); //false
在这里,obj的原型(_proto_)指向foo函数的prototype属性,foo.prototype的原型指向object.prototype,原型链的末端则为null,通过hasownproperty来查看z属性是否是obj上的,显示false,则obj上本没有z属性,但通过查找其原型链,发现在foo.prototype上有,所以obj.z=3,并且对于首例上obj.valueof()以及tostring都是object.prototype上的,所以任何一个对象都有这两个属性,因为任何一个对象的原型都是object.prototype.当然除了以下一个特例,
var obj2 = object.create(null);obj2.valueof(); //undefined
object.create()为创建一个空对象,并且此对象的原型指向参数。下面一个综合实例向大家展示一下如何实现一个class来继承另外一个class
//声明一个构造函数personfunction person(name,age){ this.name = name; this.age = age;}person.prototype.hi = function (){ console.log('hi,my name is ' + this.name +',my age is '+this.age);};person.prototype.legs_num=2;person.prototype.arms_num=2;person.prototype.walk = function (){ console.log(this.name+' is walking !');};function student(name,age,classnum){ person.call(this,name,age); this.classnum = classnum;}//创建一个空对象student.prototype = object.create(person.prototype);//constructor指定创建一个对象的函数。student.prototype.constructor = student;student.prototype.hi = function (){ console.log('hi,my name is ' + this.name +',my age is '+this.age+' and my class is '+this.classnum);};student.prototype.learns = function (sub){ console.log(this.name+' is learning '+sub);};//实例化一个对象bosnvar bosn = new student('bosn',27,'class 3');bosn.hi(); //hi,my name is bosn,my age is 27 and my class is class 3bosn.legs_num; //2bosn.walk(); //bosn is walking !bosn.learns('math'); //bosn is learning math
构造函数person与student的this指向实例化的对象(bosn),并且此对象的原型指向构造器的prototype。
我们用object.create()方法来创建一个空对象,此对象的原型事项person.prototype,这样写的好处是我们可以在不影响person.prototype属性的前提下可以自己创建studnet.prototype的任意属性,并且可以继承person.prototype上原有的属性,因为子类student是继承基类person的。如果直接写person.prototype = student.prototype,那他两同时指向一个对象,在给student.prototype添加属性的同时,person的原型链上也会增加同样的属性。
对于构造函数student里面的call方法,里面的this指向新创建的student的实例化的对象,并通过call来实现继承。
student.prototype.constructor = student,这句话的含义是指定student为创建student.prototype这个对象的函数,如果不写这句话,该对象的函数还是person。
对于继承,一共有三种方式来实现,
function person(name,age){ this.name = name; this.age = age;}function student(){}student.prototype = person.prototype; //1student.prototype = object.create(person.prototype); //2student.prototype = new person(); //3
以上这篇js原型链与继承解析(初体验)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。