Shoaib Akhtar Shoaib Akhtar - 8 months ago 26
Javascript Question

How to access other property value from function as object property value in JavaScript?

I have a JavaScript object like this:

var ali = { firstname: 'ali',
say_hi: function(firstname) {
alert("Greetings " + firstname + ", you are talking to " + this.firstname + "!");

var some_ref = ali.say_hi;

It alerts:

Greetings Sabir, you are talking to undefined!

But I want this:

Greetings Sabir, you are talking to ali!

I think
refers to window object so it gives undefined.

Can anyone please help me understand what the problem is in this and how to solve it?


what is issue in this and how to solve

The value of this depends on how the function is called. By assigning the function to a variable and calling it as f(), this will refer to the global object (or undefined in strict mode). Since there is no global variable with name firstname, this.firstname will resolve to undefined.

If you want this to refer to a specific object, you can .bind the function:

var some_ref = ali.say_hi.bind(ali);

To learn more about this, have a look at some of the many internet references: