giannis christofakis
giannis christofakis

Reputation: 8321

Property of object is not a function

Why do I get this error message 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());

Addendum

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": {} }

Proof

@dystroy was right. enter image description here

Upvotes: 1

Views: 253

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382112

You're shadowing the function here :

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

More precisely, you iterate over the property names (including the ones of the prototype chain) and you set new values to your object. When you set a value with the name of a property of the prototype, you don't change the prototype but the value that will be found with article.shortDescr will be the one of the object, not the one of the prototype.

What you do is kind of blind (you don't even have any guarantee on the order of properties) so I would recommend to change your design on this point (how ? I can't say as I really don't get the purpose).

But if you want to keep it, you may skip the prototype properties by testing using hasOwnProperty.

Upvotes: 3

Related Questions