原型链:称为“超级”链多层次的方法 [英] Prototype chain: call "super" method over multiple levels

查看:120
本文介绍了原型链:称为“超级”链多层次的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下原型链


  • SuperSuperClass

    • SuperClass

      • 班级

      每个都有一个名为的方法

      什么是常用方法用于调用相应的超类方法?

      目前我使用< ClassName> .prototype .__ proto __。< methodName> .call(this)但这看起来很奇怪。

      What is the common approach for calling the respective super class method?
      For the moment I use <ClassName>.prototype.__proto__.<methodName>.call(this) but that looks odd.

      使用以下代码控制台打印(按预期):

      Using the following code the console prints (as expected):


      • Class.prototype.do

      • SuperClass.prototype.do

      • SuperSuperClass.prototype.do

      • Class.prototype.do
      • SuperClass.prototype.do
      • SuperSuperClass.prototype.do
      SuperSuperClass = function SuperSuperClass() {}
      SuperSuperClass.prototype.do = function() {
          console.log('SuperSuperClass.prototype.do');
      };
      
      function SuperClass() {
          SuperSuperClass.call(this);
      }
      SuperClass.prototype = Object.create(SuperSuperClass.prototype);
      SuperClass.prototype.constructor = SuperClass;
      SuperClass.prototype.do = function() {
          console.log('SuperClass.prototype.do');
          SuperClass.prototype.__proto__.do.call(this);
      };
      
      function Class() {
          SuperClass.call(this);
      }
      Class.prototype = Object.create(SuperClass.prototype);
      Class.prototype.constructor = Class;
      Class.prototype.do = function() {
          console.log('Class.prototype.do');
          Class.prototype.__proto__.do.call(this);
      };
      
      var objClass = new Class();
      objClass.do();
      

      JSFiddle

      JSFiddle

      推荐答案


      什么是常用方法用于调用相应的超类方法?

      What is the common approach for calling the respective super class method?

      使用< SuperClassName> .prototype。< methodName>。调用(这)。它不仅更短,而且还具有在不支持非标准 __ proto __ 属性的环境中工作的好处。

      Use <SuperClassName>.prototype.<methodName>.call(this). It's not only shorter, but also has the benefit of working in environments that don't support the non-standard __proto__ property.

      这篇关于原型链:称为“超级”链多层次的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆