【问题标题】:How to get to my ancestor’s overridden method using Crockfords's Object.create() (Javascript)如何使用 Crockfords 的 Object.create() (Javascript) 访问我祖先的重写方法
【发布时间】:2009-11-01 13:06:13
【问题描述】:
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
var o1 = {};
o1.init = function(){
   alert('o1');
};
var o2 = Object.create(o1);
o2.init = function(){
   // how would I call my ancessors init()?
   alert('o2');
};
o2.init();

【问题讨论】:

    标签: javascript inheritance prototype object-create


    【解决方案1】:

    JavaScript 函数是对象,有两个有用的方法来调用函数:

    Function.call(scope, [arg1, ...])
    Function.apply(scope, args)
    

    您可以使用其中之一来调用父实现,将this 显式传递为scope 参数,以便在父实现中,this 引用子对象:

    var o1 = {
        name : "One",
        init : function() {
            alert("o1: " + this.name);
        }
    };
    
    var o2 = Object.create(o1);
    o2.name = "Two";
    o2.init = function() {
        o1.init.call(this);
        alert("o2: " + this name);
    };
    

    这将提醒:o1: Two 和 o2: Two。

    【讨论】:

    • 我不认为这是进入问题的精神,o2 如何知道 o1 变量的存在。对于在 Javascript 中进行面向对象开发的任何此类尝试是有意义的,您不能进行这种耦合。
    • 当然可以。如果你想调用你原型的方法实现,你必须知道你的原型。这类似于 C++ 中的类继承,您必须知道您的父类才能调用被覆盖的方法 (ParentClass::method())。
    • 我不喜欢的是你在 o2 创建后向它添加属性。使用 new 时,您可以在创建实例之前定义父子节点的构造函数。您如何使用 Object.create 完成同样的任务?
    【解决方案2】:

    也许这过于简单化了您要完成的工作...将 o1.init() 放在 o2 init 函数中是否可行?

    o2.init = function(){
       // how would I call my ancessors init()?
       alert('o2');
       o1.init();
    };
    

    出于好奇,“ancessors”是“ancestor's”的拼写错误,还是“ancessors”在这里有特定含义?你是说 o2 的“父”对象吗?

    【讨论】:

      【解决方案3】:

      在支持它的浏览器中,您可以使用Object.getPrototypeOf 函数,如下所示:

      o2.init = function(){
          Object.getPrototypeOf(this).init.call(this);
          alert('o2');
      };
      

      这将获得o2 (o1) 的原型并将其init 方法应用于此(o2),就像其他语言中的super.init()。

      更新:

      Object.getPrototypeOf 函数可以这样实现:

      if ( typeof Object.getPrototypeOf !== "function" ) 
      {
          if ( typeof ({}).__proto__ === "object" ) 
          {
              Object.getPrototypeOf = function(object)
              {
                  return object.__proto__;
              };
          } 
          else 
          {
              Object.getPrototypeOf = function(object)
              {
                  // May break if the constructor has been tampered with
                  return object.constructor.prototype;
              };
          }
      }
      

      在此链接上找到:http://ejohn.org/blog/objectgetprototypeof/

      【讨论】:

        猜你喜欢
        • 2013-12-08
        • 1970-01-01
        • 1970-01-01
        • 2011-07-11
        • 1970-01-01
        • 2020-04-20
        • 2015-10-21
        • 1970-01-01
        • 2011-06-09
        相关资源
        最近更新 更多