对象的属性不是一个函数

为什么我得到这个错误信息Property 'shortDescr' of object #<Article> is not a function

 function Article() { this.id = null; this.title = null; this.url = null; this.descr = null; this.media = null; }; Article.prototype.shortDescr = function () { if ( this.descr.length > 100) { return this.descr.substring(0,80) + ".."; } else { return this.descr; } }; var ArticleFactory = { numOfArgs : 5, inputCheck : function(args) { if (args.length != this.numOfArgs) { throw new Error("Invalid number of arguments for class `Article`"); }; return true; }, //Fill the properties with values from arguments create : function() { this.inputCheck(arguments); var counter = 0; var article = new Article(); for(propertie in article) { article[propertie] = arguments[counter++]; } return article; } }; var descr = "@hughes it actually can do both. i have an object i created with: var obj = and another object that is being passed into a callback from a server, the one passed through the callback prints with the little arrow so you can open it up, the statically created one just prints [object Object] with no arrow. "; var article = ArticleFactory.create(1,"title","url",descr,{}); console.log(article.shortDescr()); 

附录

 console.log(JSON.stringify(article, null, 4)); { "id": 1, "title": "title", "url": "url", "descr": "@hughes it actually can do both. i have an object i created with: var obj = and another object that is being passed into a callback from a server, the one passed through the callback prints with the little arrow so you can open it up, the statically created one just prints [object Object] with no arrow. ", "media": {} } 

certificate

@dystroy是对的。 在这里输入图像说明

你在这里隐藏函数:

  for(propertie in article) { article[propertie] = arguments[counter++]; } 

更确切地说,您遍历属性名称(包括原型链),并为您的对象设置新的值。 当您使用原型属性的名称设置值时,您不会更改原型,但是将使用article.shortDescrfind的值将是对象之一,而不是原型之一。

你所做的是盲目的(你甚至没有任何财产保证),所以我build议在这一点上改变你的devise(怎么样?我不能说我真的没有达到目的)。

但是如果你想保留它,你可以通过使用hasOwnPropertytesting来跳过原型属性。