Using Tencent Maps and Arrow Functions
1.Introduce key
2. Modify the source code view
2.1 Code addition
3. Page code usage
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 Arrow function
During interviews, ES6 is a major test point. When asked about arrow functions, we all say: arrow functions are very easy to use, and you no longer have to worry about the direction of this.
Interviewer: Arrow functions are very easy to use, but what are the scenarios where arrow functions are not suitable?
3.1.2 Object methods
This on the arrow function points to
y which is not defined in the window context, so undefined is returned.
whl: () => {
console.log(this === window); // => true
console.log(this.y); // undefined
}
Use ES6 short syntax, or traditional function expressions
whl() {
console.log(this === test); // => true
console.log(this.x); // 1
}
3.1.2 Prototype method
Arrow functions cause contextual errors (not allowing statements to communicate)
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
Solution: After using traditional function expressions here, the context when called will point to the newly created cat instance.
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 Event callback
Just like a btn binding click event, this in the event listening click method will point to window. When using this.innerHTML itself, it is equivalent to window.innerHTML.
const btn = document.getElementById('myButton');
btn.addEventListener('click', () => {
console.log(this === window); // => true
this.innerHTML = 'Clicked button';
});
Solution: Use function expressions instead of arrow functions
btn.addEventListener('click', function() {
console.log(this === btn); // => true
this.innerHTML = 'Clicked button';
});
3.1.2 Constructor
Arrow functions cannot be called using the new keyword: because there is no constructor method on arrow functions, they cannot be used as constructors.
const Message = (text) => {
this.text = text;
};
var helloMessage = new Message('Hello World!');
// Uncaught TypeError: Message is not a constructor
Solution
const Message = function (text) {
this.text = text;
};
var helloMessage = new Message('Hello World!');
// Uncaught TypeError: Message is not a constructor
Summarize
1. Arrow functions are suitable for issues unrelated to this, timers, and array method callbacks.
2. Arrow functions are not suitable for callbacks, event callbacks, and object methods related to this.