原文链接
箭头函数,除了帮助我们简写之外,最大的好处就是this不再被绑定在调用者,而是继承与环境对象,在哪个环境定义,this就是指的哪个环境对象。
在编写构造函数或者函数时,this的指向经常会变化,导致this.属性无法在各个函数体面使用
案例代码:
-
-
console.log(‘我是构造体‘+this);
-
-
-
-
this.timer = window.setTimeout(function () {
-
-
-
console.log(this.number);
-
-
-
-
-
-
-
为了解决this指向问题,我们可以使用bind来改变,不能使用call,apply
-
-
-
-
-
console.log(this.number);
-
-
-
-
-
var timer = window.setInterval(fn.bind(this),3000)
-
-
-
-
从上可以看出,想改变this的指向非常困难
有了箭头函数之后,一切都变得简单,不在绑定this的指向了
-
-
-
var timer = setInterval(() => {
-
-
-
console.log(this.number);
-
-
-
-
原理分析:
普通函数,this的概念是:this是JavaScript的一个关键字,他是指函数执行过程中,自动生成的一个内部对象,是指当前的对象,只在当前函数内部使用。(this对象是在运行时基于函数的执行环境绑定的:在全局函数中,this指向的是window;当函数被作为某个对象的方法调用时,this就等于那个对象)。
函数中this对象的取值,是在函数被调用执行的时候确定的。此时会创建执行上下文环境。
对于箭头函数,它没有自己的this,不能用作构造函数。
箭头函数中的this对象是定义时所在的对象,不是调用时所在的对象。
案例1
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
var hh = testObject.sayHi();
-
案例2
-
-
-
console.log(‘setTimeout普通函数的this=‘+this);
-
console.log("id: ",this.id);
-
-
-
-
-
console.log(‘setTimeout箭头函数的this=‘+this);
-
console.log("id: ",this.id);
-
-
-
-
-
-
-
-
-
=========================================
-
-
-
-
-
案例3-返回值是函数的,函数体里面的this指向的是window,和普通函数里面的this一样
-
-
-
createAnonFunction: function() {
-
-
-
-
-
-
-
-
createArrowFunction: function() {
-
-
-
-
-
-
-
-
-
-
-
> const anon = test.createAnonFunction(‘hello‘, ‘world‘);
-
> const arrow = test.createArrowFunction(‘hello‘, ‘world‘);
-
-
-
-
-
-
-
-
{ ‘0‘: ‘hello‘, ‘1‘: ‘world‘ }
案例4-函数作为参数的时候,函数体里面的this指向的是window,和普通函数里面的this一样
-
Array.prototype.myFind = function (index,callback) {
-
-
-
for (var i = 0; i < this.length; i++) {
-
-
-
-
-
-
var arr = [‘hello‘, ‘WORLD‘, ‘Whatever‘];
-
arr.myFind(1,function (item) {
-
-
-
-
特殊的案例
-
Array.prototype.myFind = function (index, callback) {
-
-
for (var i = 0; i < this.length; i++) {
-
-
callback.call(this,this[i])
-
-
-
-
-
-
var arr = [‘hello‘, ‘WORLD‘, ‘Whatever‘];
-
arr.myFind(1, function (item) {
-
-
-
-
-
-
-
-
-
ES6箭头函数(二)-this绑定
原文:https://www.cnblogs.com/MoonASixpence/p/14292960.html