简体   繁体   中英

Object property returns as undefined (JavaScript)

working on a JavaScript project. This is a little bit complicated, I know, but I'm trying to basically verify, and act on, information from Object2 through a query of an associated property in Object1 (if that makes sense)...

Object1 = function() {
    this._list = [];
};
Object1.prototype.method1 = function(param) {
     if (param == "foo") { this.method2("foo"); }
};
Object1.prototype.method2 = function(param) {
    for (var i = 0; i < this._list.length; i++) {
        if (this._list[i]._name == param) {
            console.log(this._list[i]._name); // outputs "foo"
            return this._list[i]._name // **TypeError: value is undefined**
        }
    }
};

Object2 = function(name) {
    this._name = name || "foo";
}

var object = new Object1();
var foo = new Object2("foo");
object._list.push(foo);
object.method1("foo");

I know that's a bit convoluted. My problem though, is where it returns 'param._name', it gives a TypeError. However, in the previous line, when I send it to the console, it comes out fine.

I admit that I'm a bit new to JavaScript, and even newer to OOP, so if this is a dumb, or nonsensical question, please go easy on me!

Any ideas? All ideas and suggestions are appreciated.

Thanks

I did same corrections in the code, try it:

Object1 = function() {
    this._list = [];
};
Object1.prototype.method1 = function(param) {
     if (param == "foo") { this.method2("foo"); }
};
Object1.prototype.method2 = function(param) {
    for (var i = 0; i < this._list.length; i++) {
        var item = this._list[i];
        if (item._name == param) {
            console.log(item._name); 
            return item._name;
        }
    }
};

Object2 = function(name) {
    this._name = name || "foo";
}

var object = new Object1();
var foo = new Object2("foo");
object._list.push(foo);
object.method1("foo");

Object1 Method1 should have looked like this:

Object1.prototype.method1 = function(param) {
    if (param == "foo") { return this.method2("foo"); }
};

Notice the return in there. Thank you to everyone who attempted to answer, and for your help. This post was a trainwreck from the beginning - my own fault - and I apologize for that, but I do appreciate your help and kindness in helping me work through it.

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