博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
对js原型链及继承的理解:__proto__&prototpye
阅读量:7014 次
发布时间:2019-06-28

本文共 1390 字,大约阅读时间需要 4 分钟。

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

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

每个构造函数都有一个原型对象,原型对象包含一个指向构造函数的指针(即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());        //100alert(son1.gethomemoney());    //100100;

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

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

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

 

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

 

转载于:https://www.cnblogs.com/csulym/p/5559259.html

你可能感兴趣的文章
如何让双十一数据大屏讲出故事?设计有口诀
查看>>
浮窗系列之窗口与用户输入系统
查看>>
swing效果点击下拉框自动填充文本框
查看>>
UML之活动图
查看>>
Shiro的Demo示例
查看>>
RISC领域ARM不是唯一
查看>>
数据库容灾的最高境界
查看>>
spark命令
查看>>
mysql explain中的select tables optimized away---(二)
查看>>
安装PHP5和PHP7
查看>>
邹承鲁院士谈学术文献阅读
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
android模仿铃声选择功能
查看>>
我的友情链接
查看>>
配置DHCP服务器
查看>>
trim triml trimr
查看>>
我的友情链接
查看>>
温故知新——JS中创建对象或类的方法
查看>>