function F () {
var color = "red";
this.fun = function f () {
console.log(color);
};
};
var i = new F();
i.fun();
I'm a bit confused to what new F()
/ new F
is.
Here's what I know about the new
keyword:
i) It creates {}
either in constructor function or somehow related to constructor function.
ii) this
in constructor function references this empty object and
iii) makes constructor function return this object unless you specify constructor function to return something else instead. So my first thought is that in the code above, new F()
returns { fun: [Function: f] }
.
When you console.log(new F());
what comes is slightly different:
F { fun: [Function: f] }
It look like an object, however this behaviour makes it apparent it's more complicated:
i.fun()
returns"red"
. A method of this object is able to access variables inside the constructor function that made it. If it were purely a basic object it wouldn't be able to do that.
Right now, my only idea is that new F()
is an object that is able to see the scope of the constructor function that made it.
Disclaimer: I am aware of what closures are and I know how function f
could see color
in F
. I thought what was going on was a copy of function f
was being added as a value in a brand new object which is assigned to i
. Therefore, how does function f
, in this brand new object, see the color
variable in a completely separate function, F
?
For example:
function F (v) {
var v = v;
var color = "red";
this.fun = function f () {
console.log(color);
};
};
var i = {fun: function f() {console.log(color)}};
i.fun() //returns 'color' is not defined.