Why calling Person in window scope is returning "[Object Object]" while call that in object scope is returning Object.
Asked
Active
Viewed 214 times
0
-
Well, just don't do `Person.call(window, …)`. That'll attempt to set `window.name`. And no, this has nothing to do with scopes - if you refer to the `this` keyword, that's the *context* or *receiver* of the call. – Bergi Jun 02 '17 at 04:16
2 Answers
1
global window
object already have a property of name
, and it's inside the scope of native code.

Val
- 21,938
- 10
- 68
- 86
0
window.name
is a getter/setter to set the name of the window. As such, it has to be of type string
.
Try this:
window.name = ["something", "else"];
You will see that now window.name
is set to "something,else"
; which is the result of Array.toString()
.
This is exactly what is happening here. When you call an object
's toString
, you get [object Object]
.
Your program works fine if you do not use the predefined window.name
getter/setter.
function Person(first, last) {
this.something = {
first,
last
};
}
f = {};
Person.call(f, "fsd", "fsd");
console.log(f.something);
g = window;
Person.call(g, "fsd", "fsd");
console.log(g.something);
More on getter/setters in javascript:
Setters: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/set
Getters: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/get

squgeim
- 2,321
- 1
- 14
- 21