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() { }
}
}
答案 0 :(得分:56)
你不能。
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();
答案 1 :(得分:22)
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();
答案 2 :(得分:7)
“特权方法可以访问私有变量和 方法,并且本身可以访问公共方法和 外“
例如:
function user(name) {
var username = name;
this.showGreetings = function()
{
alert(username);
}
}
答案 3 :(得分:4)
你可以尝试使用闭包的另一种方法:
function userFn(name){
return {
Methods: {
ShowGreetings: function() {
alert(name);
}
}
}
}
var user = new userFn('some user');
user.Methods.ShowGreetings();
答案 4 :(得分:4)
正如其他人所说,使用普通对象,无法从嵌套子项中查找父项。
但是,如果您使用递归ES6 Proxies作为帮助者,则可能会这样做。
我编写了一个名为ObservableSlim的库,除其他外,它允许您从子对象遍历到父对象。
这是一个简单的例子(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);
答案 5 :(得分:2)
user.Name
,因为user
实际上是单身人士。
答案 6 :(得分:1)
晚会很晚,但这有效
var user = {
Name: "Some user",
Methods() {
return {
that: this,
ShowGreetings: function() {
console.log(this.that.Name)
},
GetUserName: function() { }
}
}
}
user.Methods().ShowGreetings() // Some user
答案 7 :(得分:0)
这样怎么样?
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"
答案 8 :(得分:0)
老问题,但为什么你不能做这样的事情:
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() { }
}
}
因为您只会在实例化用户后调用user.Methods.ShowGreetings()。因此,当您想要使用其名称时,您将了解变量'user'?
答案 9 :(得分:0)
作为一种变体:
var user = (obj => {
Object.keys(obj.Methods).map(option => {
const currOpt = obj.Methods[option];
if (currOpt instanceof Function) {
obj.Methods[option] = currOpt.bind(obj);
};
});
return obj;
})({
Name: "Some user",
Methods: {
Greeting: function () { return this.Name },
GetUserName: function() { console.log(this) }
},
});
但是我不知道为什么有人可以使用这种奇怪的方法
答案 10 :(得分:0)
我知道我来晚了。 我写了这个简单的方法。假设您有:
{
subObj: {
x:'hello_world';
}
}
然后,如果要从subObj引用更大的对象,则可以将其转换为函数,并利用this
。
var tmpVal=reference_to_subObj; //keep value of subObj safe
reference_to_subObj=function(){return this;}//this returns the scope, here the parent
var parent=reference_to_subObj(); //call the function
reference_to_subObj=tmpVal; delete tmpVal; //set things back to normal
//Now you have variable 'parent'.
我使用了Function()构造函数,因为它使我可以将函数创建为字符串,因此可以将字符串作为代码传递。
function findParent(stringReference) {
Function(/*same as above, except filled in all reference_to_subObj with stringReference.*/
//stringReference is a stringified version of dot or bracket notation.
所以我可以打电话给findParent('obj.subObj')
。
答案 11 :(得分:0)
就像@Quentin说的那样,JS中没有向上的关系。但是,请尝试这种解决方法;
foo = { bar: {parent: foo} };
console.log(foo);
console.log(foo.bar.parent);
也类似于;
function Foo(){
this.bar = {parent: this}
}
foo = new Foo();
console.log(foo);
console.log(foo.bar.parent);
答案 12 :(得分:-1)
我遇到了这篇旧文章,试图记住如何解决问题。这是我使用的解决方案。它源自Harmes和Diaz的Pro JavaScript Design Patterns(Apress 2008)(第8页)。您需要声明一个函数,然后创建该函数的新实例,如下所示。注意Store方法可以访问“ this”。
function Test() {
this.x = 1;
}
Test.prototype = {
Store: function (y) { this.x = y; },
}
var t1 = new Test();
var t2 = new Test();
t1.Store(3);
t2.Store(5);
console.log(t1);
console.log(t2);
答案 13 :(得分:-2)
// 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();