首页 > 解决方案 > 'this' 创建 javascript 对象时

问题描述

我正在研究 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”关键字,我将不胜感激。

PS)我所知道的是this:当'this'写在对象中的方法中时,表示写入'this'的对象,而当它用于其他部分时,则表示全局变量。

标签: javascriptfunctionobjectvariablesthis

解决方案


推荐阅读