tags:

views:

79

answers:

3
    var user = {
        Name: "Some user",
        Methods: {
            ShowGreetings: function() {
                    // at this point i want to access variable "Name", 
                    //i dont want to use user.Name
                    // **please suggest me how??**
                 },
            GetUserName: function() { }
        }
    }
+6  A: 

You can't.

There is no upwards relationship in JavaScript.

Take for example:

var foo = {
    bar: [1,2,3]
}

var baz = {};
baz.bar = foo.bar;

The single array object now has two "parents".

What you could do is something like:

var User = function User(name) {
    this.name = name;
};

User.prototype = {};
User.prototype.ShowGreetings = function () {
    alert(this.name);
};

var user = new User('For Example');
user.ShowGreetings();
David Dorward
A: 

David Dorward's right here. The easiest solution, tho, would be to access user.Name, since user is effectively a singleton.

David Hedlund
A: 

You can try another approach using a closure:

function userFn(name){
    return {
     Methods: {
      ShowGreetings: function() {
       alert(name);
      }
     }
    }
}
var user = new userFn('some user');
user.Methods.ShowGreetings();
Mic