对js原型链及继承的理解:__proto__&prototpye

首先我们来理解一下原型链的概念:

要理解原型链必须知道构造函数、原型和实例的关系:

每个构造函数都有一个原型对象,原型对象包含一个指向构造函数的指针(即prototype),而实例则包含一个指向原型对象的内部指针(即__proto__)。

 

var father = function() {
    this.relation = "father";
}
father.prototype.money = function() {
    this.money = 100000;
}
var son = new father();
alert(son.__proto__ == father.prototype);        //true

我们可以看到son在使用原型继承了father之后,son.__proto__ == father.prototype为true。

这是因为在var son = new father()的过程中,实际上是完成了以下代码:

var son = {};
son.__proto__ = father.prototype;
father.call(son);

那么__proto__到底是什么呢?每个对象在初始化时内部都有一个属性__proto__,当我们访问一个对象的属性时,当这个对象本身不存在该属性,则会去对象的__proto__

里找,这个__proto__又会有自己的__proto__,于是就这样一直找下去,这就是我们平时所说的原型链的概念。

了解了原型链的概念之后,我们再说一下如何实现继承。

下面的代码就是继承的简单例子:

var father = function() {
    this.money = 100000;
}
father.prototype.getmoney = function() {
    return this.money;
}
var son = function(){
    this.mymoney = 100;
}
son.prototype = new father();
son.prototype.getmymoney = function(){
    return this.mymoney;
}
son.prototype.gethomemoney = function(){
  return this.mymoney + this.money;
}
var son1 = new son();
alert(son1.getmymoney());        //100
alert(son1.gethomemoney());    //100100;

上面的代码中,father类有money属性值为100000,son类有mymoney属性值为100。son类继承了father类,得到了money值。同时son类有两个方法分别为:

getmymoney()和gethomemoney()前者返回son自身的属性mymoney,后者返回自身属性mymoney及继承得到的属性money之和。

继承的方式为:son.prototype = new father();

 

以上为我个人的理解,不对或不足的地方希望大家斧正。

 

posted @ 2016-06-04 18:09  一个大木头  阅读(733)  评论(0编辑  收藏  举报