[英]Object property returns as undefined (JavaScript)
working on a JavaScript project. 在一个JavaScript项目上工作。 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中的关联属性来验证和处理Object2中的信息(如果有意义)...
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.
我的问题是,它返回“ param._name”,并给出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! 我承认我对JavaScript有点陌生,甚至对OOP还是陌生的,因此,如果这是一个愚蠢或荒谬的问题,请对我轻松一点!
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 Method1应该看起来像这样:
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.
这篇文章从一开始就是一场沉船事故-我自己的错-我为此表示歉意,但是我非常感谢您的帮助和帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.