理解 JavaScript 对象和函数中的“this”

理解 javascript 对象和函数中的“this”

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 对象中的一个变量(对象属性),因此它返回分配给它的值。

虽然上述情况在现实场景中可能没有必要,但这只是对其底层工作原理的基本解释。

让我们看另一个例子:

    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,对吗?就范围内的使用而言,我们也不应该失眠。

以上就是理解 JavaScript 对象和函数中的“this”的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1493381.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 15:38:39
下一篇 2025年12月19日 15:38:48

相关推荐

发表回复

登录后才能评论
关注微信