ES6箭头函数this指向和arguments知识
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>箭头函数</title>
<style type="text/css">
html {height: 100%;}
body {width: 200px;height: 100%;position: relative;padding: 0;margin: 0;}
</style>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/1.9.0/jquery.js"></script>
<script>
var obj = {
data: ['beijing', 'shanghai'],
init: function () {
console.log(arguments[0].name);//xutongbao
var test = () => {
console.log(this.data);//["beijing", "shanghai"]
console.log(arguments[0].name); //xutongbao
}
test();
}
}
obj.init({name: 'xutongbao'});
var test = () => {
console.log(arguments); //未定义 ReferenceError: arguments is not defined
}
test({name: 'xutongbao'});
</script>
</body>
</html>
由于this
在箭头函数中已经按照词法作用域绑定了,所以,用call()
或者apply()
调用箭头函数时,无法对this
进行绑定,即传入的第一个参数被忽略:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>箭头函数</title>
<style type="text/css">
</style>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/1.9.0/jquery.js"></script>
<script>
var obj = {
birth: 1990,
getAge: function (year) {
var b = this.birth; // 1990
var fn = (y) => y - this.birth; // this.birth仍是1990
return fn.call({birth:2000}, year);
}
};
var age = obj.getAge(2018); // 28
console.log(28)
</script>
</body>
</html>