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() { }
}
}
Run Code Online (Sandbox Code Playgroud)
Que*_*tin 56
你不能.
JavaScript中没有向上的关系.
举个例子:
var foo = {
bar: [1,2,3]
}
var baz = {};
baz.bar = foo.bar;
Run Code Online (Sandbox Code Playgroud)
单个数组对象现在有两个"父".
你能做的是:
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();
Run Code Online (Sandbox Code Playgroud)
Mik*_*Mik 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();
Run Code Online (Sandbox Code Playgroud)
"特权方法能够访问私有变量和方法,并且本身可以访问公共方法和外部"
例如:
function user(name) {
var username = name;
this.showGreetings = function()
{
alert(username);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53761 次 |
| 最近记录: |