javascript - '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();
PS)我所知道的是this:当'this'写在对象中的方法中时,表示写入'this'的对象,而当它用于其他部分时,则表示全局变量。
解决方案
推荐阅读
- kaios - 不知道如何在 KaiOS 中杀死应用程序进程
- javascript - 错误调用 API
- text - 预处理文本,以便检测到没有分隔空格(或连字符分隔)的两个单词
- java - Android在视图组内设置视图位置
- spring - Read multiple properties file in one go using Spring Boot?
- regex - 我正在尝试从文件中提取一行
- r - R-使用存储在服务器上的文件部署闪亮应用程序的问题
- spring - 配置 Spring Boot 以使用自定义访问令牌转换器
- android - 请求与我的库相同的导入的 Android 项目
- vee-validate - 如何在不同名称的 vee-validate 中显示服务器错误?