为什么会收到此错误消息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": {} }
@dystroy是对的。
答案 0 :(得分:3)
你在这里隐藏了这个功能:
for(propertie in article) {
article[propertie] = arguments[counter++];
}
更准确地说,您遍历属性名称(包括原型链的名称)并为对象设置新值。当您使用原型的属性名称设置值时,您不会更改原型,但使用article.shortDescr
找到的值将是对象之一,而不是原型之一。
你做的是一种盲目的(你甚至对财产的顺序都没有任何保证)所以我建议在这一点上改变你的设计(怎么样?我不能说因为我真的没有得到目的)。
但是如果你想保留它,你可以通过使用hasOwnProperty
进行测试来跳过原型属性。