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中访问父对象
IT技术
javascript
2021-01-20 17:30:32
6个回答
你不能。
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();
“特权方法能够访问私有变量和方法,并且本身可以被公共方法和外部访问”
例如:
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();
正如其他人所说,使用普通对象不可能从嵌套子项中查找父项。
但是,如果您使用递归ES6 代理作为助手,则是可能的。
我编写了一个名为ObservableSlim的库,除其他外,它允许您从子对象向上遍历到父对象。
这是一个简单的示例(jsFiddle 演示):
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);
其它你可能感兴趣的问题