如何在函数签名中使用 'this' 关键字来设置默认参数?
How can you use the 'this' keyword inside of a function signature to set a default parameter?
我有一个绑定到 React 组件的函数:
functionName(param1, param2 = this.state.field) {
}
我从未听说过 'this' 关键字在 Javascript 的函数签名中使用,我想知道 'this' 的上下文是包含对象还是全局对象范围。在我可以在签名中正确使用 'this' 之前,此函数是否需要绑定到正确的上下文?
如果函数在 class 中,它正在从 React 库扩展 React.Component class。 "this" 关键字在其 class 的上下文中引用当前对象。例如:
import React from 'react';
class example extends React.Component {
this.state = {
field: "this variable!"
}
functionName(param1, param2 = this.state.field) {
console.log(param2);
}
}
如您所见,this.state 是示例 class 的 属性,只是在第二个参数处被调用,这将 return 字段的值 [= this.state 对象的 27=]。
如果你想知道它是否可行。好吧,JavaScript是一种多范式语言,如果打算在函数式范式中使用它,这绝对是可以接受的。
I am wondering if the context of 'this' will be the containing object or the global scope.
都没有。默认值不在函数外求值,而是 。 this
关键字将指向与方法主体中相同的值 - 调用的接收者。因此,如果该函数绑定到您的 React 组件,那么 this
就是这样。
我有一个绑定到 React 组件的函数:
functionName(param1, param2 = this.state.field) {
}
我从未听说过 'this' 关键字在 Javascript 的函数签名中使用,我想知道 'this' 的上下文是包含对象还是全局对象范围。在我可以在签名中正确使用 'this' 之前,此函数是否需要绑定到正确的上下文?
如果函数在 class 中,它正在从 React 库扩展 React.Component class。 "this" 关键字在其 class 的上下文中引用当前对象。例如:
import React from 'react';
class example extends React.Component {
this.state = {
field: "this variable!"
}
functionName(param1, param2 = this.state.field) {
console.log(param2);
}
}
如您所见,this.state 是示例 class 的 属性,只是在第二个参数处被调用,这将 return 字段的值 [= this.state 对象的 27=]。
如果你想知道它是否可行。好吧,JavaScript是一种多范式语言,如果打算在函数式范式中使用它,这绝对是可以接受的。
I am wondering if the context of 'this' will be the containing object or the global scope.
都没有。默认值不在函数外求值,而是 this
关键字将指向与方法主体中相同的值 - 调用的接收者。因此,如果该函数绑定到您的 React 组件,那么 this
就是这样。