使用腾讯地图和箭头函数的使用

1.引入key

在这里插入图片描述

2.修改源码视图

在这里插入图片描述

2.1 代码添加

在这里插入图片描述

3.页面代码使用

uni.chooseLocation({
	success: res => {
		console.log('位置名称:' + res.name);
		console.log('详细地址:' + res.address);
		console.log('纬度:' + res.latitude);
		console.log('经度:' + res.longitude);
		console.log(res.address + res.name);
		this.value8 = res.address + res.name; //赋值给data中value8
		// console.log(this.value8)
	}
});

3.1 箭头函数

面试中,ES6 是一大考点,当被问到箭头函数时,我们都会说:箭头函数很好用,而且再也不用操心 this 的指向了

面试官:箭头函数是挺好用的,那有哪些不适合使用箭头函数的场景呢?

3.1.2 对象的方法

箭头函数上的this指向window
上下文中没有定义y,就返回undefined

    whl: () => {
        console.log(this === window); // => true
        console.log(this.y); // undefined
    }

用 ES6 的短语法,或者传统的函数表达式

	whl() {
	    console.log(this === test); // => true
	    console.log(this.x); // 1
	}

3.1.2 原型方法

箭头函数会导致上下文错误(不能够让语句进行交流)

function Cat (name) {
    this.name = name;
}

Cat.prototype.sayCatName = () => {
    console.log(this === window); // => true
    return this.name;
};

const cat = new Cat('Miao');
cat.sayCatName(); // => undefined

解决方法:这里使用了传统的函数表达式后,被调用时的上下文就会指向新创建的cat实例

function Cat (name) {
    this.name = name;
}

Cat.prototype.sayCatName = function () {
    console.log(this === cat); // => true
    return this.name;
};


const cat = new Cat('Miao');
cat.sayCatName(); // => Miao
3.1.2 事件的回调

就类似一个btn绑定点击事件,在事件监听click方法中的this会指向window,当自身使用this.innerHTML等价于window.innerHTML

const btn = document.getElementById('myButton');
btn.addEventListener('click', () => {
  console.log(this === window); // => true
  this.innerHTML = 'Clicked button';
});

解决方法:用函数表达式代替箭头函数

btn.addEventListener('click', function() {
    console.log(this === btn); // => true
    this.innerHTML = 'Clicked button';
});

3.1.2 构造函数

箭头函数不能使用new关键字调用:因为箭头函数上没有constructor方法,所以不能用作构造函数

const Message = (text) => {
    this.text = text;
};

var helloMessage = new Message('Hello World!');
// Uncaught TypeError: Message is not a constructor

解决方法

const Message = function (text)  {
    this.text = text;
};

var helloMessage = new Message('Hello World!');
// Uncaught TypeError: Message is not a constructor

总结

1.箭头函数适合与this无关的问题,定时器,数组的方法回调
2.箭头函数不适合与this有关的回调,事件回调,对象的方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值