为什么我收到此错误消息 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是正确的。
您在这里隐藏函数:
for(propertie in article) {
article[propertie] = arguments[counter++];
}
更准确地说,您遍历属性名称(包括原型链的属性名称),并为对象设置新值。当使用原型属性的名称设置值时,您不会更改原型,但是将找到的值将是article.shortDescr
对象中的一个,而不是原型中的一个。
您所做的工作是盲目的(您甚至无法保证属性的顺序),所以我建议您在这一点上更改设计(怎么做?我不能说,因为我确实没有达到目的) )。
但是,如果要保留它,可以通过使用测试跳过原型属性hasOwnProperty
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句