功能箭头_经典箭头功能

功能箭头

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对象调用了经典函数。 因此, thisobj

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

I hope this has been helpful. Happy coding!

希望这有用。 编码愉快!

翻译自: https://medium.com/swlh/classic-and-arrow-functions-this-in-javascript-18c585af18f8

功能箭头

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值