简体   繁体   中英

Referencing an object through a variable in JavaScript

I've defined the methods "checkThreshold" and "checkOtherObject" in my prototype. checkOtherObject iterates across objects listed in attribute "nextDev" and is supposed to invoke checkThreshold for each object, thus:

// Protoype
function foo(otherObject) {
    // attributes       
    this.nextDev=otherObject; // comma-delimited list of objects

    // Method that references another method
    this.checkOtherObject= function() {
    successorList=this.nextDev.split(",");
        for (var i=0; i<successorList.length;i++) {
            successorList[i]['checkThreshold']();
        }
    }  
    // Method referenced by checkOtherObject
    this.checkThreshold = function () {
        <Do Stuff>     
    }
//Instantiations
var A = new foo ("B");
var B = new foo ("");

Thus, expected behavior is that A.checkOtherObject would invoke B.checkThreshold, but when I get to that line, B.checkThreshold isn't invoked. What am I doing wrong?

The root problem: you're trying to assign value of instances in theirselves. Note: what you're doing is still wrong, otherObject is a object, but it's a String object and it's not referring to the current foo 's instance ( this ).

this.nextDev = otherObject

Other problem is that you're calling String().checkThreshold , but not foo().checkThreshold . You can check that at your statements:

successorList = this.nextDev.split(",");
for (var i = 0; i < successorList.length; i++) {
    successorList[i]['checkThreshold']();
}

As you can see you're iterating string literals. String().split returns a object with string literals back, not a list with foo() 's .

/* confirm that the successorList is a array object */
successorList instanceof Array; // true
/* confirm that the first successorList's item is a string object */
typeof successorList[0] === "string"; // true

I'm basically not sure about what's your objective. It looks like you've a extra-ordinary giant confusion between String objects and objects. Maybe you want to store nextDev out of foo() , and at nextDev you want to store a Array object containing instances of foo ? Then try:

var devs = [];

function foo(string) {
    devs.push(this);
}

foo.prototype = {
    checkOtherObjects: function() {
        var me = this;
        var myIndex;
        var i = 0, len = devs.length;
        for (; i < len; ++i) {
            if (devs[i] === me) {
                myIndex = i;
                break;
            }
        }
        for (i = myIndex + 1; i < len; ++i)
            devs[i].checkThresold()
    }
};

To offer a bit of a better explanation - yes, you CAN use window[successorList[i]] , however, that is highly, highly not recommended, and here's why:

This becomes an issue if the variables no longer in the global scope. For example, if you place the code inside of a function, including an IIFE or a document ready function, you can no longer reference your variables from the window object, unless you were to declare them with window.A, window.B, but declaring global variables like that can get so messy, especially when working with other libraries/plugins.

So...how can you work around these issues? Simple - pass the object itself as @Bergi mentioned instead of passing the string that contains the name of the variable.

Here's what the code would look like:

 // Protoype function foo(otherObject) { this.nextDev = otherObject || []; // Method that references another method this.checkOtherObject = function() { this.nextDev.forEach(function(obj, index) { obj.checkThreshold(); }); }; // Method referenced by checkOtherObject this.checkThreshold = function() { // Do Stuff console.log("Checking Threshold for: ", this); }; } //Instantiations var B = new foo(null); var A = new foo([B]); //or [B, C, D, E, ...] A.checkOtherObject(); 

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