Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access parent object in javascript

Tags:

javascript

    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() { }         }     } 
like image 923
Praveen Prasad Avatar asked Nov 24 '09 12:11

Praveen Prasad


People also ask

What is parent object in Javascript?

The object to which a given property or method belongs.

Which object is the parent object?

Parent object and child object in the lookup relationship are determined purely on the requirement. Example: The object which has the more number of records will be the parent object and the object which has fewer records is considered as the child object.

Is parent object for all the objects in Javascript?

The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java. ...


2 Answers

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(); 
like image 185
Quentin Avatar answered Oct 03 '22 02:10

Quentin


var user = {     Name: "Some user",     Methods: {         ShowGreetings: function() {             alert(this.Parent.Name); // "this" is the Methods object         },         GetUserName: function() { }     },     Init: function() {         this.Methods.Parent = this; // it allows the Methods object to know who its Parent is         delete this.Init; // if you don't need the Init method anymore after the you instanced the object you can remove it         return this; // it gives back the object itself to instance it     } }.Init(); 
like image 29
Mik Avatar answered Oct 03 '22 02:10

Mik