2009-11-24 25 views
30
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() { } 
     } 
    } 
+2

posible duplicado de [matriz de acceso de los padres de Javascript objeto] (http://stackoverflow.com/questions/183702/access-parents-parent-from- javascript-object) –

Respuesta

47

No puede.

No existe una relación ascendente en JavaScript.

Tomemos por ejemplo:

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

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

El único objeto de matriz tiene ahora dos "padres".

Lo que podría hacer es algo como:

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

David de Dorward aquí. La solución más fácil, sin embargo, sería acceder al user.Name, ya que user es efectivamente un singleton.

2

Puede jugar diferente usando un cierre:

function userFn(name){ 
    return { 
     Methods: { 
      ShowGreetings: function() { 
       alert(name); 
      } 
     } 
    } 
} 
var user = new userFn('some user'); 
user.Methods.ShowGreetings(); 
16
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(); 
-1
// 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(); 
+3

Agregue algunas explicaciones para su respuesta ... –

6

Crockford:

"Un método privilegiado es capaz de acceder a las variables privadas y métodos y es accesible para los métodos públicos y el fuera de "

Por ejemplo:

function user(name) { 
    var username = name; 

    this.showGreetings = function() 
    { 
     alert(username); 
    } 
} 
+1

Si ajusta 'this.showGreetings' en un objeto no funcionará. – zachdyer

0

¿Qué hay de esta manera?

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

para que pueda acceder user.Name en ShowGreetings

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" 
0

pregunta Viejo pero ¿por qué no puedes hacer algo como esto:

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??** 
        var thisName = user.Name; //<<<<<<<<< 
       }, 
      GetUserName: function() { } 
     } 
    } 

ya que sólo se llame usuario .Methods.ShowGreetings() después de que el usuario ha sido instanciado. Entonces, ¿sabrá sobre la variable 'usuario' cuando quiera usar su nombre?

2

Como han dicho otros, con un objeto simple no es posible buscar un elemento primario de un elemento secundario anidado.

Sin embargo, es posible si emplea recursivo ES6 Proxies como ayudantes.

He escrito una biblioteca llamada ObservableSlim que, entre otras cosas, le permite atravesar desde un objeto secundario hasta el elemento principal.

Aquí hay un ejemplo simple (jsFiddle demo):

var test = {"hello":{"foo":{"bar":"world"}}}; 
var proxy = ObservableSlim.create(test, true, function() { return false }); 

function traverseUp(childObj) { 
    console.log(JSON.stringify(childObj.__getParent())); // returns test.hello: {"foo":{"bar":"world"}} 
    console.log(childObj.__getParent(2)); // attempts to traverse up two levels, returns undefined because test.hello does not have a parent object 
}; 

traverseUp(proxy.hello.foo); 
Cuestiones relacionadas