首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

js面向对象学习八 原型链的原理 _proto_

2012-11-25 
js面向对象学习8 原型链的原理 __proto__?说到prototype,就不得不先说下new的过程。我们先看看这样一段代码

js面向对象学习8 原型链的原理 __proto__

?

说到prototype,就不得不先说下new的过程。

我们先看看这样一段代码:

?

var Person = function () { };Person.prototype.Say = function () {alert("Person say");}Person.prototype.Salary = 50000;var Programmer = function () { };Programmer.prototype = new Person();Programmer.prototype.WriteCode = function () {alert("programmer writes code");};Programmer.prototype.Salary = 500;var p = new Programmer();p.Say();p.WriteCode();alert(p.Salary);

?我们来做这样的推导:

var p=new Programmer()可以得出p.__proto__=Programmer.prototype;

而在上面我们指定了Programmer.prototype=new Person();我们来这样拆分,var p1=new Person();Programmer.prototype=p1;那么:

p1.__proto__=Person.prototype;

Programmer.prototype.__proto__=Person.prototype;

由根据上面得到p.__proto__=Programmer.prototype。可以得到p.__proto__.__proto__=Person.prototype。

好,算清楚了之后我们来看上面的结果,p.Say()。由于p没有Say这个属性,于是去p.__proto__,也就是 Programmer.prototype,也就是p1中去找,由于p1中也没有Say,那就去p.__proto__.__proto__,也就是 Person.prototype中去找,于是就找到了alert(“Person say”)的方法。

其余的也都是同样的道理。

这也就是原型链的实现原理。

最后,其实prototype只是一个假象,他在实现原型链中只是起到了一个辅助作用,换句话说,他只是在new的时候有着一定的价值,而原型链的本质,其实在于__proto__!

热点排行
Bad Request.