GloryOfThe80s
GloryOfThe80s

Reputation: 161

Evaluated function as an object property in JavaScript

I am defining an object literal in JavaScript, but when I try to create a property that is a called function, I get a Uncaught ReferenceError: xxx is not defined error.

Here's an example:

var person = {
    name : 'Saucy Jack',

    convenienceHook : this.getName('some predefined string'),

    getName : function(string) {
        console.log(this.name + string);
    }
};

This errors saying Uncaught ReferenceError: convenienceHook is not defined.

Nor does it work if I assign the property outside the object definition:

var person = {
    name : 'Saucy Jack',

    getName : function(string) {
        console.log(this.name + string);
    }
};

person.convenienceHook = person.getName('some predefined string');
person.convenienceHook(); //returns error 

What am I missing?

Upvotes: 1

Views: 228

Answers (4)

Esa Hannila
Esa Hannila

Reputation: 1318

This should work

var person = {
name: "Saucy Jack", 
convenienceHook: function() { return this.getName("Predefined text") },
getName: function(string) { 
    string=string||"";
    return this.name + string; } 
}

Upvotes: 0

Amit
Amit

Reputation: 46361

The reason your first attempt fails is that this is not person, it's whatever this is in your current scope. could be global, or could be something else if that code is within a function.

Upvotes: 0

Doron Brikman
Doron Brikman

Reputation: 2584

What you assigning is not a function, you need for example to return a function from the getName function, so the convenienceHook will be a function:

getName : function() {
    return function() {
        console.log(this.name);
    };
}

Upvotes: 0

Ry-
Ry-

Reputation: 225263

Here:

var person = {
    name : 'Saucy Jack',

    convenienceHook : getname('some predefined string'),

    getName : function(string) {
        console.log(this.name + string);
    }
};

you’re calling a function called getname that doesn’t exist. getName is not a property on person yet, because getname('some predefined string') has to be evaluated before the object can exist, since it’s part of the object literal. Even if it did exist, though, you still wouldn’t be able to call it as a bare getname, and even if it did, you would have to capitalize getName properly.

Your second approach also just calls person.getName. It looks like you want to make another function that will call getName:

var person = {
    name : 'Saucy Jack',

    convenienceHook : function() {
        return this.getName('some predefined string');
    },

    getName : function(string) {
        console.log(this.name + string);
    }
};

Upvotes: 4

Related Questions