简体   繁体   English

JavaScript 函数在将 `this` 作为参数传递时会出错

[英]JavaScript function gives error when passed `this` as an argument

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

It throws the error Unexpected token this .它抛出错误Unexpected token this So why doesn't JavaScript accept this as an argument?那么为什么 JavaScript 不接受this作为参数呢?

this is a reserved keyword so it can't be used as a variable name. this是一个保留关键字,因此不能用作变量名。

If you want to override the this value for a function, you can use call or apply . 如果要覆盖函数的this值,则可以使用callapply

 function log() { console.log(this); } log.apply({ custom: "this value" }); 

this has special meaning in the language. this在语言中有特殊含义。 It's an identifier, but can only be defined automatically in specific situations, never explicitly by the developer. 它是一个标识符,但是只能在特定情况下自动定义,而开发人员则不能明确定义。

Other identifiers that are automatically defined can still be defined by the developer, like arguments , undefined and window , though it should be avoided in most cases. 开发人员仍然可以定义其他自动定义的标识符,例如argumentsundefinedwindow ,尽管在大多数情况下应避免使用。


To add clarity, in programming an identifier is a label used by a programmer to reference a value. 为了清楚起见,在编程时,标识符是程序员用来引用值的标签。

In JS, this is indeed a keyword, which, according to ECMAScript semantics, prevents it from being explicitly declared as an identifier. 在JS中, this确实是一个关键字,根据ECMAScript语义,它可以防止将其明确声明为标识符。 This does not mean that it isn't an identifier at all, which it clearly is since it will always let the programmer reference a value. 这并不意味着它根本不是标识符,因为它总是让程序员引用一个值,所以它显然是标识符。

So something being a keyword does not mean that it isn't an identifier. 因此,作为关键字的东西并不意味着它不是标识符。 It does mean though that in JS, you don't have the option of explicitly declaring an identifier with that name, though other languages do sometimes allow this. 这确实意味着,尽管在JS中,您没有选择显式声明带有该名称的标识符的选项,尽管其他语言有时也允许这样做。

Being this is a reserved keyword in JavaScript, you are not allowed that as a formal parameter to a function. 由于this是JavaScript中的保留关键字,因此不允许将其作为函数的形式参数。

You can pass this as an argument to a function when you call or invoke that function but not as a formal parameter when you define your function. 您可以在调用或调用函数时将this作为参数传递给函数,而在定义函数时则不能将其作为形式参数传递。

 function log(that) { console.log(that); } log(this); // passed as an argument 

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

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