在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() { } } } 

你不能。

JavaScript中没有向上的关系。

举个例子:

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

单个数组对象现在有两个“父母”。

你可以做的是这样的:

 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(); 
 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(); 

Crockford :

“一种特权的方法是能够访问私有variables和方法,并且本身可以访问公共方法和外部的”

例如:

 function user(name) { var username = name; this.showGreetings = function() { alert(username); } } 

你可以尝试使用闭包的另一种方法:

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

大卫·多尔沃德就在这里。 最简单的解决scheme将是访问user.Name ,因为user实际上是一个单身人士。

这样呢?

 user.Methods.ShowGreetings.call(user, args); 

所以你可以在ShowGreetings中访问user.Name

 var user = { Name: "Some user", Methods: { ShowGreetings: function(arg) { console.log(arg, this.Name); }, GetUserName: function() { } }, Init: function() { this.Methods.ShowGreetings.call(this, 1); } }; user.Init(); // => 1 "Some user" 
 // Make user global window.user = { name: "Some user", methods: { showGreetings: function () { window.alert("Hello " + this.getUserName()); }, getUserName: function () { return this.getParent().name; } } }; // Add some JavaScript magic (function () { var makeClass = function (className) { createClass.call(this, className); for (key in this[className]) { if (typeof this[className][key] === "object") { makeClass.call(this[className], key); } } } var createClass = function (className) { // private var _parent = this; var _namespace = className; // public this[className] = this[className] || {}; this[className].getType = function () { var o = this, ret = ""; while (typeof o.getParent === "function") { ret = o.getNamespace() + (ret.length === 0 ? "" : ".") + ret; o = o.getParent(); } return ret; }; this[className].getParent = function () { return _parent; }; this[className].getNamespace = function () { return _namespace; } }; makeClass.call(window, "user"); })(); user.methods.showGreetings();