access parent object in javascript

2019-01-02 18:31发布

    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
10条回答
宁负流年不负卿
2楼-- · 2019-01-02 18:39

You can try another approach using a closure:

function userFn(name){
    return {
        Methods: {
            ShowGreetings: function() {
                alert(name);
            }
        }
    }
}
var user = new userFn('some user');
user.Methods.ShowGreetings();
查看更多
公子世无双
3楼-- · 2019-01-02 18:40

As others have said, with a plain object it is not possible to lookup a parent from a nested child.

However, it is possible if you employ recursive ES6 Proxies as helpers.

I've written a library called ObservableSlim that, among other things, allows you to traverse up from a child object to the parent.

Here's a simple example (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);
查看更多
临风纵饮
4楼-- · 2019-01-02 18:43

Crockford:

"A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside"

For example:

function user(name) {
     var username = name;

     this.showGreetings = function()
     {
       alert(username);
     }  
}
查看更多
唯独是你
5楼-- · 2019-01-02 18:45
// 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();
查看更多
几人难应
6楼-- · 2019-01-02 18:51

David Dorward's right here. The easiest solution, tho, would be to access user.Name, since user is effectively a singleton.

查看更多
不再属于我。
7楼-- · 2019-01-02 18:53

You can't.

There is no upwards relationship in JavaScript.

Take for example:

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

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

The single array object now has two "parents".

What you could do is something like:

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();
查看更多
登录 后发表回答