Reputation: 43
When I run in the console, I don't quite follow why it yields a result of zero. I thought both MyObject and myFunc are global. What concept am I missing to understand this properly?
myObject = {
length: 400,
};
function myFunc () {
return console.log(this.length);
}
myFunc(myObject.length); // equals zero
Upvotes: 0
Views: 32
Reputation: 12508
You're passing the object as a parameter, but you're not receiving it in the function. this
in the context of myFunc
is not the object myObject
. It is the window
object.
To achieve what you're trying to do, modify your code like so:
myObject = {
length: 400,
};
function myFunc (obj) {
return console.log(obj.length);
}
myFunc(myObject); // equals zero
Note:
To verify that this
is the window
object, see this fiddle where I've modified your console line to be return console.log(this);
. The console outputs the Window
object.
Upvotes: 0
Reputation: 1074969
It's showing you the value of window.length
(which is the number of frames/iframes in the document). To have myFunc
show you the value of the length
of the object you pass into it, you'd have to use that argument:
function myFunc (obj) {
return console.log(obj.length);
}
If you're trying to explore implicit globals (your myObject
is an implicit global; they're a Bad Thing(tm)), then myFunc
should be called with no arguments and should use myObject.length
or possibly this.myObject.length
(which come to the same thing).
Upvotes: 2