Javascript 对象的属性不是函数
为什么我会收到此错误消息Javascript 对象的属性不是函数,javascript,node.js,prototype,Javascript,Node.js,Prototype,为什么我会收到此错误消息对象的属性'shortDescr'不是函数 function Article() { this.id = null; this.title = null; this.url = null; this.descr = null; this.media = null; }; Article.prototype.shortDescr = function () { if ( th
对象的属性'shortDescr'不是函数
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());
补遗
证明
@戴斯特罗伊是对的。
您在此处隐藏函数:
for(propertie in article) {
article[propertie] = arguments[counter++];
}
更准确地说,您迭代属性名称(包括原型链的名称),并为对象设置新值。当您使用原型属性的名称设置值时,您不会更改原型,但将在文章中找到的值。shortDescr
将是对象的值,而不是原型的值
你所做的有点盲目(你甚至不能保证房产的顺序),所以我建议你在这一点上改变你的设计(怎么做?我不能说,因为我真的不明白目的)
但是如果您想保留它,可以通过使用
hasOwnProperty
进行测试来跳过原型属性 如何实例化文章
?您在实例化时是否忘记使用new
?很抱歉,我只是编辑了我的问题并填写了所需的信息,如果我遗漏了其他信息,请提醒我。您所做的事情真的很奇怪。我确信这是一个bug,但我猜不出你想做什么。我对javascript有点陌生,我正在试验,我想做的是跳过每个属性的赋值,而是使用循环和参数
对象,这对我来说是新事物,可以跳过所有这些。我必须学会正确拼写属性。
for(propertie in article) {
article[propertie] = arguments[counter++];
}