javascript - 看不到从子对象添加到原型(prototype)的属性

标签 javascript node.js inheritance prototype

我需要一些帮助来理解 javascript protoypal 继承是如何工作的……或者更确切地说,为什么它没有按照我的预期去做。

本质上,我正在尝试建立从 new 返回的模板化对象陈述。我在 utils.js 中有一个通用构造函数模块将参数对象的任何值分配给相应的模板对象,我返回修改后的模板对象作为调用 new 的结果.


module.exports.ctor = ctor;

//Mapped object constructor
function ctor(template) {

  return function(args) {
     var s, t, p;

    //guard against being used without new
    //courtesy of John Resig http://ejohn.org/blog/simple-class-instantiation/
    if (!(this instanceof arguments.callee)) {
      throw new Error("Constructor called without 'new'");
    }

    //create a deep copy of `template` to modify
    t = JSON.parse(JSON.stringify(template));
    args = args === 'undefined' ? {} : args;   

    // copy values of matching properties from `args` to `t`
    // (uses Crockford's `typeOf` function http://javascript.crockford.com/remedial.html)
    for (p in t) {
      if (args[p]) {
        s = typeOf(t[p]);

        if (s === 'function' || s === 'null') {
          /* do nothing */
        } else if (s === 'array') {
          t[p] = t[p].concat(args[p]);
        } else {
          t[p] = args[p];
        }
      }
    }

    return t;
  };
}

这是通用构造函数如何在 Contact 上工作的示例模板对象,带有一些 Contact添加到 prototype 的特定属性对象:

var template = {
    email: null,
    phone: null,
    address: []
};

var Contact = require('../util').ctor(template);

Contact.prototype.template = template;

Contact.prototype.print = function() {
  var str = this.email + '\n';
  str += this.phone + '\n';
  for (var i = 0; i < this.address.length; i++) {
    str += this.address[i].toString() + '\n';
  }
};

module.exports = Contact;

我的期望是 template属性(property)和print函数将在返回对象的链中可用,但看起来它们不可用(来自 Node REPL):

> var Contact = require('./mapping/Contact');
undefined
> var c = new Contact();
undefined
> c.print
undefined
> c.template
undefined
> c
{ email: '', phone: '', address: [] }

有人可以向我解释为什么我要明确地向 Contact 的原型(prototype)添加属性吗? ,那些属性对返回的对象不可用?

最佳答案

这是因为 ctor() 导致构造函数返回 t,这是一个普通的通用对象。由于构造函数返回的是普通对象,因此您丢失了原型(prototype)。不返回 t,而是将 t 的属性复制到 this:

for (var k in t) {
    this[k] = t[k];
}

然后,不要返回任何东西。或者,如果您愿意,返回 this

关于javascript - 看不到从子对象添加到原型(prototype)的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13898526/

相关文章:

javascript - 将 Razor 语法变量传递给 Html Helper 的 javascript onclick

node.js - 如何在 hapi js 中以流形式回复文件?

node.js - Mongoose userModel 未定义

node.js - 尝试创建 React App 时出现 web pack 问题

c++ - 模板类派生自非模板基类 : No access to base class variables?

c++ - 将派生类转换为具有相同公共(public)函数的泛型类类型,同时仍然可以调用派生类的函数

C++模板类继承

c# - 如何根据 session 变量以编程方式更改表单操作?

javascript - 如何通过单击按钮获取 UL/LI 框的选定 ID - Jquery

javascript - jQuery.fn 的目的是什么