
js 对象作用域中的 this 关键字
在 javascript 中,了解 this 关键字的内容、方式和位置可能是编写实际有效的代码和在编码时抓狂的区别。
这个关键字
在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 对象中的一个变量(对象属性),因此它返回分配给它的值。
虽然上述情况在现实场景中可能没有必要,但这只是对其底层工作原理的基本解释。
让我们看另一个例子:
ECTouch是上海商创网络科技有限公司推出的一套基于 PHP 和 MySQL 数据库构建的开源且易于使用的移动商城网店系统!应用于各种服务器平台的高效、快速和易于管理的网店解决方案,采用稳定的MVC框架开发,完美对接ecshop系统与模板堂众多模板,为中小企业提供最佳的移动电商解决方案。ECTouch程序源代码完全无加密。安装时只需将已集成的文件夹放进指定位置,通过浏览器访问一键安装,无需对已有
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());
输出1
obj.b() 执行函数,this 解析为 obj 对象范围并返回 a
立即学习“Java免费学习笔记(深入)”;
的值输出2
箭头函数将其解析为全局范围,即使它们是在对象内声明的。这里,this 解析为全局作用域(窗口),变量 a 不存在于全局作用域中,因此返回 undefined。
输出3
obj.b从obj对象返回一个函数(它不执行它;函数调用中的括号表示执行),返回的函数被分配给测试变量,并且该函数在全局范围(窗口)中执行,变量 a 在全局作用域中不存在,因此返回 undefined。
输出4
obj.c从obj对象返回一个函数(它不执行它;函数调用中的括号表示执行),返回的函数被分配给testarrow变量,并且该函数在全局范围(窗口)中执行,箭头函数通常会将 this 解析到全局作用域,变量 a 不存在于全局作用域中,因此返回 undefined。
好了,伙计们。我希望您已经了解 javascript 中的工作原理的基础知识。不再在箭头函数中使用 this,对吗?就范围内的使用而言,我们也不应该失眠。









