shivtej
shivtej

Reputation: 663

How to pass object properties to a function from object itself?

I want to pass an object property to a global function and want to save return value in a new object property . What I tried:

var Tools = {
     id : "tools" ,
     key : myfunc(this.id)      //I also tried Tools["id"] and id .
};

Here is the function:

function myfunc(tmp){
     return tmp;
}

I want to use Tools.key not Tools.key() that's why I'm not using following code:

key : function(){ 
     return myfunc(this.id);
}

Upvotes: 0

Views: 935

Answers (3)

kuroi neko
kuroi neko

Reputation: 8641

I assume you don't want to recompute the key each time you access it, so the get solution seems a bit inefficient to me.

The second solution avoids unnecessary computations, but does not take full advantage of the object mechanism.

I would rather do something like this:

var Tool = function (id) {
    this.id = id;
    this.key = myFunc (id);
    return this;
}

this way you actually make id and key attributes of the Tool object, instead of returning a generic object with the same fields.

If you want to add class methods later, you will see the advantage.

Assume you define a method like this:

Tool.prototype.getCash = function (sum) {
    if (!checkKey (this.key)) callTheCops();
    return sum;
}

If you create a Tool instance using a constructor that returns an unnamed structure like
{ id: id , key: myFunc(key) };
with something like
var tool = Tool (123);,
the tool variable will not inherit the getCash() method and you'll be stuck with a structure that won't know anything about getting cash.

With the above constructor, you can create a class instance like so:
var tool =newTool (123);
and do whatever the class allows with it.

Upvotes: 0

laruiss
laruiss

Reputation: 3816

This is what you might want to do:

var tools = {
    id: 7,
    get key() { 
        var key = 'Key is ' + this.id; // Do something with this.id
        return key;
    },
};

tools.key; // "Key is 7"

You should read MDN to learn and understand more

Notice that I removed the capital 'T' from tools: since it is not a function that should be used as a constructor, it should not begin with a capital letter.

Upvotes: 2

Valery Bugakov
Valery Bugakov

Reputation: 355

You're trying to get uninitialized property of the object (id). At the moment of creating Tools object id property of it isn't set yet, that's why you're getting undefined there.

You should store Id in variable and pass to your function and property, or create a class Tools and than pass an Id to constructor.

var Tool = function(id) {
    return { id: id, key: myFunc(id) };
}
var myTool = Tool(55);
myTool.key // will return 55

Upvotes: 1

Related Questions