在设置ECharts参数的时候经常会碰到一个问题就是this指向的问题,主动改变this指向常用的有apply call bind 这边仅做个人学习记录
情况是这样的我在从https://madeapie.com/#/上找到满意的图表 把代码copy下来之后,会发现里面有挺多函数套函数的情况,使用起来就很容易导致this指向的混淆,用两个例子来理解一下,看懂第一个例子就行,第二个例子其实同理:
一、函数套函数
| Fn () { |
| console.log('Fn', this); |
| function fn () { |
| console.log('fn', this); |
| } |
| fn() |
| } |
复制
此时的打印

首先我们要知道通常情况下this指向的是调用它的对象,(这边的打印fn中this的指向为undefined的原因是什么 我并不知道,希望有知道的大佬能在评论区指点一下!(感谢,真的很想知道为什么!),但我知道怎么让fn中也能让this指向Vue,通常我们会这么做
| Fn () { |
| let _this = this |
| function fn () { |
| console.log('fn', _this ); |
| } |
| fn() |
| } |
| |
| |
复制
| Fn () { |
| console.log('Fn', this); |
| function fn () { |
| console.log('fn', this ); |
| } |
| fn.apply(this) |
| } |
| |
| |
复制
| Fn () { |
| console.log('Fn', this); |
| function fn () { |
| console.log('fn', this ); |
| } |
| fn.call(this) |
| } |
| |
| |
复制
上面三种方法都可以解决这个问题,还有一种方法比较麻烦,就是将fn从Fn里面抽离出来,这种方法在没有传参的情况下还行,有传参就有点麻烦
二、函数套对象,对象中有函数
| Fn () { |
| console.log('Fn', this); |
| let obj = { |
| name:'name', |
| fn: function () { |
| console.log('fn', this); |
| } |
| } |
| obj.fn() |
| }, |
| |
| |
复制
此时的打印

Fn仍指向Vue,fn现在指向的是obj对象,那如何让他们都指向Vue,也就是说让fn指向Vue呢?
首先可以告诉的是,第一个例子的三种方法都可行。这边新增一个方式
| Fn () { |
| console.log('Fn', this); |
| let obj = { |
| name: 'name', |
| fn: () => { |
| console.log('fn', this); |
| } |
| } |
| obj.fn() |
| } |
| |
| |
复制
补充:
| console.log(Object.prototype.toString.call(123)) ; |
| console.log(Object.prototype.toString.call('123')); |
| console.log(Object.prototype.toString.call(undefined)); |
| console.log(Object.prototype.toString.call(true)); |
| console.log(Object.prototype.toString.call({})); |
| console.log(Object.prototype.toString.call([])); |
| console.log(Object.prototype.toString.call(function(){})); |
复制
-
apply和call都可以用来改变this,不同在于apply的第二个参数必须传入数组,call不用
| apply: |
| fn().apply(obj,[a,b,c]) |
| |
| call: |
| fn().apply(obj,a,b,c) |
复制
| let arr = [] |
| Math.max.apply(null, arr) |
| Math.min.apply(null, arr) |
复制