I used the chrome console and had some other findings
function Man(){
this.Man = "Peter";
console.log("this", this);
}
Above this refers to Window. If you call the function Man()
nothing is returned since the function does not return anything but sets the property Man on the window-object to be Peter
. Your line Man.Man
should return undefined
in chrome. If you use Man().Man
you will get undefined as well since this
refers to the window object and the function Man()
has no property Man
. You could write
function Man(){
this.Man = "Peter";
return this.Man;
}
This returns the value Peter
. If you want to have a property Man
you could use a constructor function write
// set this.Man == window.Man to Peter
function Man() { this.Man = "Peter"; }
// create an constructor for each object Man
Man.prototype = { constructor: this.Man }
// create an object
var man = new Man();
// call his property which was set in the constructor of the prototype
man.Man;
Please ask for more help if anything is unclear.
Update as response to the comment
You can use a constructor without using prototype (see examples at mdn or this question if you use this syntax:
function Box(color) // Constructor
{
this.color = color;
}
var redBox = new Box("red");
var blueBox = new Box("blue");
redBox.color; // returns red
blueBox.color; // returns blue
To understand where this
refers to you can take a look at understanding javascript this. In the box-example this
refers to the new instance (object) of the "underlying class function". In function Man(){this.Man = "Peter"}
the this
refers to this.window. You can read more about protype in this book.