I'm studying javaScript object. I learned to create objects in this format, but I don't understand 'this' keyword very well.
var Person = function(name, age){
this.name = name;
this.age = age;
}
I think the 'this' written here is global variable. However, even though there are no names and ages defined as global variables, this constructor works well.like this.
var Person = function(name, age){
this.name = name;
this.age = age;
}
var john = new Person('john',19);
console.log(john.name); //result : 'john'
console.log(john.age); //result : 19
I don't know why it works like this. When I write code like this,
var Person = function(){
console.log(this); //result : window
console.log(this.name); //result : '' // <--I don't know why empty string is printed on this part, too.
console.log(this.job); //result : undefined
}
Person();
P.S)What I know is that this : When 'this' is written in the method in the object means the object in which 'this' is written, and that when it is used in other parts, it means global variable.