【问题标题】:placing inheritance, create methods - inside or outside objects?放置继承,创建方法 - 内部还是外部对象?
【发布时间】:2012-07-08 20:43:01
【问题描述】:

我是新来的,所以我希望我没有违反任何规则......

所以我正在研究 JavaScript 中的对象继承......并且正在为这件事找出“我的”规则......现在我遇到了“一些”问题......

这是我喜欢做的事情:

我喜欢有一个方法(函数),它更像是我正在创建的对象的标识符,这个方法也是对象的创建者......但是我也希望使用同一个对象来实例化“数据类型”创建的对象(我猜代码解释得更多......这是我坚持的部分)

    TRecord = function() {
      this.Class = 'TRecord';
      F = function() {};
      F.prototype = arguments[0]; //args is an object (se below)
      return(new F());
    };

    TRecord.create = function(O) { // this method will not be executed as I like
        if(O) alert(O.Class);      // inside above object when define there with
        <new O object created and returned - code missing>
    };                             // this.create = function(){};
                                   // but if defined here it will, se below...

    TMessage = TRecord({
      'Class': 'TMessage',
      'msgID': Number(0),
      'data': Object('Hello')
    });

    aMSG = TRecord.create(TMessage); // the TMessage instance will be created
                                     // with the above method... and
    alert(aMSG.Class);               // will output TMessage...

为什么我不能在 TRecord 中实现 TRecord.create 函数?

... 我在发布整个 source.js 时遇到了一些麻烦(格式不起作用)所以这将不得不到期,但是我确实有一些其他构造函数/创建函数用于“真实”函数(类)对象而不是记录(数据对象) ... 行得通 - 虽然这些实现有点不同,但支持深度继承...

【问题讨论】:

  • 主题也没有显示为键入...
  • 我从标题中删除了一些杂乱无章的内容 - 但它仍然毫无意义。请提供描述问题的标题。您不需要添加诸如“javascript”之类的关键字,这就是标签的用途。

标签: javascript class inheritance prototype


【解决方案1】:

this 关键字是指调用函数的范围。在您的示例中:

TMessage = TRecord({...});

将使用globalwindow 对象作为其范围调用TRecord,或者在严格模式下调用undefinedthis 关键字仅指构造函数内部的新对象,因为 new 关键字如何将调用与新作用域结合起来。

更多信息请见https://developer.mozilla.org/en/JavaScript/Reference/Operators/this

【讨论】:

    【解决方案2】:

    不完全确定您要做什么,但看起来TRecord 应该是某种类工厂。试试

    TRecord = function() {
      var F = function() {};
      F.prototype = arguments[0];
      var result = new F();
      result.Class = 'TRecord';
      return result;
    };
    

    【讨论】:

    • 不是真正的 TRecord() 返回的东西正在工作... TRecord.create 返回的东西
    • 迟到了——但我想澄清一下! TRecord 创建作为参数传递的对象的新对象,这就像 F.prototype = {anuthing inside},但是我的 TRecord 用于保持不同类型的对象彼此(使其更易于阅读)所以 TMessage = TRecord({'property':value}) 生成一个 TRecord 类型的新 TMessage... TMessage 然后用于创建工作数据类型,如 aMSG = TRecord.create('TMessage'),此方法可用于其他几个 TRecord类型...(这个 JS 解决方法是我的阅读)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    相关资源
    最近更新 更多