我在几个地方读过,关键的区别在于this
在箭头函数中的词法约束。这一切都很好,但我实际上并不知道这意味着什么。
我知道这意味着它在定义函数主体的大括号范围内是唯一的,但我实际上无法告诉您以下代码的输出,因为我不知道this
指的是什么,除非它指的是胖箭头函数本身....这似乎没有用。
var testFunction = () => { console.log(this) };
testFunction();
我在几个地方读过,关键的区别在于this
在箭头函数中的词法约束。这一切都很好,但我实际上并不知道这意味着什么。
我知道这意味着它在定义函数主体的大括号范围内是唯一的,但我实际上无法告诉您以下代码的输出,因为我不知道this
指的是什么,除非它指的是胖箭头函数本身....这似乎没有用。
var testFunction = () => { console.log(this) };
testFunction();
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
因此,要直接回答您的问题,this
您的箭头函数内部将具有与分配箭头函数之前相同的值。
为了提供全局,我将解释动态绑定和词法绑定。
this
指调用该方法的对象。这是关于 SO 的一个经常阅读的句子。但它仍然只是一个短语,相当抽象。这句话有对应的代码模式吗?
就在这里:
const o = {
m() { console.log(this) }
}
// the important patterns: applying methods
o.m(); // logs o
o["m"](); // logs o
m
是一种方法,因为它依赖于this
. o.m()
或o["m"]()
手段m
适用于o
。这些模式是我们著名短语的 Javascript 翻译。
您应该注意另一个重要的代码模式:
"use strict";
const o = {
m() { console.log(this) }
}
// m is passed to f as a callback
function f(m) { m() }
// another important pattern: passing methods
f(o.m); // logs undefined
f(o["m"]); // logs undefined
它与前面的模式非常相似,只是缺少括号。但后果是相当大的:当你传递m
给函数时,你会从它的对象/上下文中f
拉出来。它现在被连根拔起,什么都没有(假定为严格模式)。m
o
this
箭头函数没有自己的this
//绑定super
。arguments
它们从父词法范围继承它们:
const toString = Object.prototype.toString;
const o = {
foo: () => console.log("window", toString.call(this)),
bar() {
const baz = () => console.log("o", toString.call(this));
baz();
}
}
o.foo() // logs window [object Window]
o.bar() // logs o [object Object]
除了全局范围(Window
在浏览器中)之外,只有函数能够在 Javascript 中形成一个范围(以及{}
ES2015 中的块)。当o.foo
箭头函数被调用时,没有baz
可以继承它的周围函数this
。因此,它捕获this
绑定到Window
对象的全局范围的绑定。
当baz
被 调用时o.bar
,箭头函数被o.bar
(o.bar
形成其父词法范围) 包围并且可以继承o.bar
的this
绑定。o.bar
被调用o
,因此它this
是必然的o
。
希望这个代码展示能给你更清晰的想法。基本上,箭头函数中的“this”是“this”的当前上下文版本。见代码:
// 'this' in normal function & arrow function
var this1 = {
number: 123,
logFunction: function () { console.log(this); },
logArrow: () => console.log(this)
};
this1.logFunction(); // Object { number: 123}
this1.logArrow(); // Window
箭头函数this
在 Es6 中指向周围的父级,这意味着它不像 ES5 中的匿名函数那样作用域...
这是避免将 var self 分配给 ES5 中广泛使用的 this 的非常有用的方法......
看下面的例子,在对象内部分配一个函数:
var checkThis = {
normalFunction: function () { console.log(this); },
arrowFunction: () => console.log(this)
};
checkThis.normalFunction(); //Object {}
checkThis.arrowFunction(); //Window {external: Object, chrome: Object, document: document, tmpDebug: "", j: 0…}
您可以尝试按照下面的方式来理解它
// whatever here it is, function or fat arrow or literally object declare
// in short, a pair of curly braces should be appeared here, eg:
function f() {
// the 'this' here is the 'this' in fat arrow function below, they are
// bind together right here
// if 'this' is meaningful here, eg. this === awesomeObject is true
console.log(this) // [object awesomeObject]
let a = (...param) => {
// 'this is meaningful here too.
console.log(this) // [object awesomeObject]
}
所以胖箭头函数中的“this”没有绑定,这意味着你不能在这里绑定任何东西,.apply 不会,.call 不会,.bind 不会。当您在文本编辑器中写下代码文本时,胖箭头函数中的“this”被绑定。胖箭头函数中的“this”在这里实际上是有意义的。您在文本编辑器中编写的代码就是您的应用在 repl 中运行的内容。除非您在文本编辑器中更改它,否则胖箭头中绑定的“this”永远不会改变。对不起我的泳池英语...
箭头函数永远不会与this
关键字绑定
var env = "globalOutside";
var checkThis = {env: "insideNewObject", arrowFunc: () => {
console.log("environment: ", this.env);
} }
checkThis.arrowFunc() // expected answer is environment: globalOutside
// Now General function
var env = "globalOutside";
var checkThis = {env: "insideNewObject", generalFunc: function() {
console.log("environment: ", this.env);
} }
checkThis.generalFunc() // expected answer is enviroment: insideNewObject
// Hence proving that arrow function never binds with 'this'
在另一个例子中,如果你点击下面的年龄按钮
<script>
var person = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: function() {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
var person2 = {
firstName: 'John',
surname: 'Jones',
dob: new Date('1990-01-01'),
isMarried: false,
age: () => {
return new Date().getFullYear() - this.dob.getFullYear();
}
};
</script>
<input type=button onClick="alert(person2.age());" value="Age">
它会抛出这样的异常
×JavaScript 错误:未捕获的 TypeError:无法读取第 18 行未定义的属性“getFullYear”
但是如果你改变 person2 的这一行
return new Date().getFullYear() - this.dob.getFullYear();
至
return new Date().getFullYear() - person2.dob.getFullYear();
它将起作用,因为此范围已在 person2 中更改
箭头函数与常规函数的区别:(取自w3schools)
使用箭头函数没有 this 的绑定。
在常规函数中,this 关键字表示调用函数的对象,可以是窗口、文档、按钮或其他任何东西。
对于箭头函数,this 关键字始终表示定义箭头函数的对象。
// Regular Function:
hello = function() {
document.getElementById("demo").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello);
// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
// -------------------------------------------
// Arrow function
hello2 = () => {
document.getElementById("demo2").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello2);
// A button object calls the function:
document.getElementById("btn2").addEventListener("click", hello2);
<p><i>With a regular function this represents the <b>object that calls the function</b>:</i></p>
<button id='btn'>click me regular function</button>
<p id="demo">Regular function: </p>
<hr>
<p><i>With arrow function this represents the <b>owner of the function(=the window object)</b>:</i></p>
<button id='btn2'>click me arrow function</button>
<p id="demo2">Arrow function: </p>
在箭头函数中使用时,this将始终引用全局对象。使用常规函数声明来引用本地对象。此外,您可以使用对象名称作为上下文(object.method,而不是 this.method),以便它引用本地对象而不是全局(窗口)。
一个相关问题:
我们从这里知道:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
对 this 或 super 没有自己的绑定,不应用作方法。
箭头函数根据箭头函数在其中定义的范围建立“this” 。
使用箭头函数有问题,所以创建了一个类(可以是函数),并在箭头函数中访问类变量,从而使用不带关键字this
的箭头函数实现更小的函数:function
class MyClassOrFunction {
values = [];
size = () => this.values.length;
isEmpty = () => this.size() === 0;
}
let obj = new MyClassOrFunction();
obj.size(); // function call here
你也可以有一个像这样的getter,它没有关键字,但由于语句function
有点长,也可以访问其他成员函数:return
class MyClassOrFunction {
values = [];
size = () => this.values.length;
get length() { return this.size(); }
}
let obj = new MyClassOrFunction();
obj.length; // NOTE: no function call here