zoukankan      html  css  js  c++  java
  • 原型链继承需要注意的问题

    背景:

      JavaScript的继承基本上可以分为两大类,一类是使用class定义的类使用extends继承;另一类是使用function定义的类基于原型链的继承。之前自己看过一遍JavaScript高级程序设计,但是今天在第二遍快速过的时候发现了两个之前自己没有注意的点。

    需要注意点:

      1. 给原型添加新的方法的时候一定需要注意覆盖的问题。

     1 function SuperType() {
     2     this.property = true
     3 }
     4 SuperType.prototype.getSuperValue = function () {
     5     return this.property
     6 }
     7 function ASubType() {
     8     this.subproperty = false
     9 }
    10 ASubType.prototype = new SuperType()
    11 ASubType.prototype = {
    12     getASubValue: function () {
    13         return this.subproperty
    14     },
    15     someOtherMethod: function () {
    16         return false
    17     }
    18 }
    19 let a = new ASubType()
    20 // TypeError: a.getSuperValue is not a function
    21 console.log(a.getSuperValue())

      理解:

        ①. 其实这个就可以理解为覆盖(和函数的覆盖相似)

      2. 给原型添加方法的代码一定要放在替换原型语句之后。

     1 function SuperType() {
     2     this.property = true
     3 }
     4 SuperType.prototype.getSuperValue = function () {
     5     return this.property
     6 }
     7 function ASubType() {
     8     this.subproperty = false
     9 }
    10 ASubType.prototype.getSubValue = function() {
    11     return this.subproperty
    12 }
    13 
    14 ASubType.prototype = new SuperType()
    15 
    16 ASubType.prototype.getSuperValue = function () {
    17     return false
    18 }
    19 let a = new ASubType()
    20 // TypeError: a.getSubValue is not a function
    21 console.log(a.getSubValue())

      理解:

        ①. 在上述代码第10行,给ASubType添加原型方法时,添加的方法处于一个空位置原型中(这里的空位置指的是没有显示原型对象)。

        ②. 在第14行重新定义原型对象的时候,将ASubType的原型方法定义为SuperType,此时SuperType替代了那个空位置,所以自然第10添加的原型对象就无意义了

    参考资料:

      1. 《JavaScript高级程序设计(第三版)》第六章165页

  • 相关阅读:
    MVC常见问题小总结
    IIS 7的备份与恢复
    [译]Professional ASP.NET MVC3(03) Chapter 1:Getting Started(下)
    跟小静读CLR via C#(18)——Enum
    跟小静读CLR via C#(17)接口
    跟小静学MVC3[02]从注册模块实战MVC新特性
    高性能网站14条——读《高性能网站建设指南》
    [译]Professional ASP.NET MVC3(02) Chapter 1:Getting Started(中)
    [译]Professional ASP.NET MVC3(01)Chapter 1:Getting Started(上)
    从零开始MVC3—Music Store实例&Controller
  • 原文地址:https://www.cnblogs.com/oulae/p/11173715.html
Copyright © 2011-2022 走看看