码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-06-04 19:34:38      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

 

var father = function() {
    this.relation = "father";
}
father.prototype.money = function() {
    this.money = 100000;
}
var father1 = new father();
alert(father1.__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();

 

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

 

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

标签:

原文地址:http://www.cnblogs.com/csulym/p/5559259.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!