
在javascript中,这是一个关键字(保留字),也就是说,它不能用作变量名。
在 javascript 代码中,这用于表示范围。简而言之,作用域是包含一行或多行代码的代码块。它可以表示整个代码(全局范围)或大括号内的代码行 {...}
var a = 1;
//varaible "a" can be accessed any where within the global scope
function sayhello(){
var message = "hello";
console.log(message);
};
//the variable "message" is not accessible in the global scope
//varaible "a" can be accessed any where within the global scope
var a = 1;
console.log(this.a); // output is 1; this refers to the global scope here, the variable "a" is in the global scope.
function sayhello(){
var message = "hello";
console.log(this.message);
};
sayhello(); // undefined
您可能想知道为什么上面代码片段中的 sayhello() 函数返回未定义,因为 this 引用了 sayhello() 函数作用域。在你急于说之前,这是 javascript 的另一个怪癖。让我们深入探讨一下。
var a = 1;
console.log(this.a); // output is 1; this refers to the global scope here, the variable "a" is in the global scope.
function sayhello(){
var message = "hello";
console.log(this.message);
};
sayhello(); // undefined
sayhello() 函数在全局范围内执行,这意味着 sayhello() 的执行会将其解析为全局范围(window 对象;更像是 window.message)。全局作用域中没有名为 message 的变量,因此它返回 undefined (您可以尝试将名为 message 的变量添加到全局作用域中,看看会发生什么。)。可能的解决方案如下所示:
var person = {
message: "hello",
sayhello: function(){
console.log(this.message);
}
};
person.sayhello(); // hello
这里,sayhello() 函数是 person 对象中的一个属性,执行该函数会将其解析为 person 对象的范围,而不是 window 对象。 message 是 person 对象中的一个变量(对象属性),因此它返回分配给它的值。
虽然上述情况在现实场景中可能没有必要,但这只是对其底层工作原理的基本解释。
让我们看另一个例子:
类似智能机器人程序,以聊天对话框的界面显示,通过输入问题、或点击交谈记录中的超链接进行查询,从而获取访客需要了解的资料等信息。系统自动保留用户访问信息及操作记录。后台有详细的设置和查询模块。适用领域:无人职守的客服系统自助问答系统智能机器人开发文档、资源管理系统……基本功能:设置对话界面的显示参数设置各类展示广告根据来访次数显示不同的欢迎词整合其他程序。
4
const obj = {
a: 1,
b: function() {
return this.a;
},
c: () => {
return this.a;
}
};
// Output 1: 1
console.log(obj.b());
// Output 2: undefined
console.log(obj.c());
const test = obj.b;
// Output 3: undefined
console.log(test());
const testArrow = obj.c;
// Output 4: undefined
console.log(testArrow());
obj.b() 执行函数,this 解析为 obj 对象范围并返回 a
立即学习“Java免费学习笔记(深入)”;
的值箭头函数将其解析为全局范围,即使它们是在对象内声明的。这里,this 解析为全局作用域(窗口),变量 a 不存在于全局作用域中,因此返回 undefined。
obj.b从obj对象返回一个函数(它不执行它;函数调用中的括号表示执行),返回的函数被分配给测试变量,并且该函数在全局范围(窗口)中执行,变量 a 在全局作用域中不存在,因此返回 undefined。
obj.c从obj对象返回一个函数(它不执行它;函数调用中的括号表示执行),返回的函数被分配给testarrow变量,并且该函数在全局范围(窗口)中执行,箭头函数通常会将 this 解析到全局作用域,变量 a 不存在于全局作用域中,因此返回 undefined。
好了,伙计们。我希望您已经了解 javascript 中的工作原理的基础知识。不再在箭头函数中使用 this,对吗?就范围内的使用而言,我们也不应该失眠。
以上就是理解 JavaScript 对象和函数中的“this”的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号