I am trying to review some basic Javascript using an online environment where print() is allowed. However, when I try to call say() on an instance of the person, it is saying that "say" is not a function. I have tried this in several different environments with their version of print (be it writeln, console.log, or whatever) and it's always saying it's not a function.
//JavaScript-C24.2.0 (SpiderMonkey)
print("Hello, world!")
function person(name, age) {
this.name = name;
this.age = age;
this.say = function () {
print(this.name);
}
}
var arrayz = [];
arrayz.push(person("bob",20));
arrayz.push(person("sally",19));
arrayz.push(person("joe",22));
for (var z in arrayz) {
z.say();
}
I'm doing it in just the same manner as this is: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS
So I don't see what I'm doing wrong. Can someone please help me with what I'm doing wrong here?
The correct code should be:
print("Hello, world!")
function person(name, age) {
this.name = name;
this.age = age;
this.say = function () {
print(this.name);
}
}
var arrayz = [];
arrayz.push(new person("bob",20));
arrayz.push(new person("sally",19));
arrayz.push(new person("joe",22));
for (var z of arrayz) {
z.say();
}
Let me explain. The first difference is the new
keyword. This creates a new instance of the function you've made as an object. The way you did it just called person
as a function. So it stores the returned value of person
into the the array instead of the object instance. Since person
doesn't return a value it stores undefined
into your array.
More info about the new
operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
Second, you used var z in arrayz
. When using in
, z
becomes the index instead of the object. If you want the z
to be the value of the array item you should use var z of arrayz
More info about for...in
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
More info about for...of
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
Using new person(...)
instead of person(...)
will create the object you want, filled with properties you specified by writing this.xxx = yyy
in the function body.
You are simply calling the function, meaning that you are trying to get its the return value and push it in the array.
I don't see any return statement in your function person
, so the result is undefined
.
You have pushed 3 undefined
in your array, and you try to execute say()
on them.
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.