功能箭头
Classic and arrow functions in Javascript have a few differences. Arguably, the most impactful is their relationship to thethis
property.
Javascript中的经典和箭头功能有一些区别。 可以说,最有影响力的是他们与this
财产的关系。
For a classic function, this
refers to the function’s execution context or what can also be thought of as the object that is calling the function. In the example below, a classic function is called by the obj
object. Therefore, its this
is obj
.
对于经典函数, this
指的是函数的执行上下文或也可以视为调用函数的对象。 在下面的示例中, obj
对象调用了经典函数。 因此, this
是obj
。
const obj= {
name: "Eli",
test: function () {
console.log(this, this.name)
}
}obj.test() // {name: "Eli", test: ƒ} "Eli"
If we implement the same code with an arrow function, this
will change to the lexical scope of obj
, which is the window. Since the window does not have a name
property, only one value is logged to the console.
如果我们使用箭头函数实现相同的代码, this
它将更改为obj
的词法范围,即窗口。 由于窗口没有name
属性,因此只有一个值记录到控制台。
const obj= {
name: "Eli",
test: () => {
console.log(this, this.name)
}
}obj.test() // Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
Another way to understand the difference is how classic function’s this
changes from non-strict to strict mode. In non-strict mode, a classic function direct call (see below) will make this
default to the window.
理解上的差异的另一种方法是经典的功能如何的this
从非严格严格的模式改变。 在非严格模式下,经典函数直接调用(请参见下文)会将this
默认为窗口。
function classic1(){
console.log(this)
}classic1() // Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
…but in strict mode a direct call will return undefined. That is because the function was not called as a method or property of an object.
…但是在严格模式下,直接调用将返回未定义。 那是因为没有将函数称为对象的方法或属性。
function classic2(){
'use strict'
console.log(this)
}classic2() // undefined
翻译自: https://medium.com/swlh/classic-and-arrow-functions-this-in-javascript-18c585af18f8
功能箭头