简体   繁体   English

来自 MDN 和书籍的 JavaScript `this` 示例不起作用......为什么?

[英]JavaScript `this` examples from MDN and books not working ... why?

I'm trying to understand JS this because it has been too confusing to me for too long, and no one has given me an explanation I can comprehend so far.我想了解JS this是因为它已经太混乱了我太久,也没有人给我一个解释,我可以迄今理解。 I went to MDN and tried a simple code example from their documentation.我去了 MDN 并从他们的文档中尝试了一个简单的代码示例。 The code straight copied from their page is as follows (console logs are my only addition):从他们的页面直接复制的代码如下(控制台日志是我唯一的补充):

var obj = {a: 'Custom'}
var a = 'Global'
function whatsThis () {
    return this.a
}

console.log(whatsThis())
console.log(whatsThis.call(obj))
console.log(whatsThis.apply(obj))

According to MDN, the output should be:根据 MDN,输出应该是:

Global
Custom
Custom

Instead, I get相反,我得到

undefined
Custom
Custom

Incredulous, I tried an example from the somewhat-famous You Don't Know JS series, chapter 2 of book 2, regarding this .难以置信,我尝试从一定程度上著名的一个例子你不知道JS系列,书2章2,关于this I tried the following example, verbatim:我逐字地尝试了以下示例:

function foo() {
    console.log( this.a );
}

var a = 2;

foo();

The book says the output should be 2 , but I get undefined .这本书说输出应该是2 ,但我得到undefined

This is exactly why I want to learn more about this , but even books and MDN straight code examples are failing for me, making it very difficult to get my mind wrapped around a core concept of JS.这正是我想了解更多相关信息的this ,但即使是书籍和 MDN 直接代码示例也不适合我,这让我很难将注意力集中在 JS 的核心概念上。 Please help me set this straight in my head.请帮我把这个放在我的脑海里。

Variables declared with var in a Node.js module don't end up on the global object – modules have their own scope.在 Node.js 模块中用var声明的变量不会在全局对象上结束——模块有自己的作用域。 You can put the properties you want to read on the global object explicitly:您可以显式地将要读取的属性放在全局对象上:

global.a = 'Global';
global.a = 2;

(In browsers, it's window instead of global , or you can use the new portable globalThis for both.) (在浏览器中,它是window而不是global ,或者您可以为两者使用新的可移植globalThis 。)

However, you won't need to worry about this behaviour too much.但是,您无需过多担心这种行为。 In strict mode , which you should always use (and which will be applied automatically inside new features like classes and ES modules), the this of a plain function call like whatsThis() is just undefined .严格模式下,您应该始终使用(并且将在类和 ES 模块等新功能中自动应用),像whatsThis() this的普通函数调用的whatsThis()只是undefined

 'use strict'; function whatsThis() { console.log('this is ' + this); } let obj = { whatsThis, }; whatsThis(); whatsThis.call('a string'); obj.whatsThis();

The global object in Node should essentially never be used, and declaring variables with var at the top level in browser scripts is similarly bad practice. Node 中的全局对象本质上不应该被使用,并且在浏览器脚本的顶层使用var声明变量同样是不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM