无法看到从子对象添加到原型的属性

我需要一些帮助了解如何JavaScript protoypalinheritance工作…或者说为什么它不做我期待它做的事情。

基本上我试图build立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属性和printfunction将在返回的对象的链中可用,但看起来它们不是(从节点REPL):

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

有人可以向我解释为什么如果我明确地将属性添加到Contact的原型,这些属性不可用于返回的对象?

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

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

那么,不要回报任何东西。 或者,如果您愿意,还可以退货。