我正在研究javaScript对象。 我学会了以这种格式创建对象,但是我不太了解'this'关键字。
var Person = function(name, age){
this.name = name;
this.age = age;
}
我认为这里写的“ 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
我不知道为什么会这样。 当我这样写代码时
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();
附:我知道的是: 当在方法中写入“ this”时,对象是指写入“ this”的对象,而在其他部分中使用时,则表示全局变量。