简体   繁体   中英

how to access javascript constructor variables in nested prototype

I am unable to access the constructor variable in RandObj.exampleFunction (this.name = "steven") in Example 1 due to the fact that the scoping of this in RandObj is limited to just the RandObj itself. This is because I have what I believe is a nested prototype going on, but I would like to keep this nested prototype since it is necessary for what I am trying to build out. I understand that I can access 'this.name' using example 2, but I would like to keep the structure that I have in example 1.

//EXAMPLE 1
define(function() {
    'use strict';

    var Wrapper = function(nameIn) {
        this.name = nameIn;
    };

    Wrapper.prototype = {
        RandObj: {
            exampleFunction: function() {
                this.name = "steven";
            }
        }
    };
    return Wrapper;
});


//EXAMPLE 2
define(function() {
    'use strict';

    var Wrapper = function(nameIn) {
        this.name = nameIn;
    };

    Wrapper.prototype = {
        exampleFunction: function() {
            this.name = "steven";
        }
    };
    return Wrapper;
});

In this scenario, you can access the name is by first executing the function, then accessing the name.

Wrapper.prototype.RandObj.exampleFunction(); 
Wrapper.prototype.RandObj.name; 

But I'm not sure what you are trying to achieve so I don't know if this is helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM