标签:ted htm cte 出现 UNC 冲突 避免 get name
使用箭头函数定义对象方法
let obj = {
value: 1,
getValue: () => console.log(this.value);
}
obj.getValue(); // undefined
定义原型方法时
function Foo() {
this.value = 1;
}
Foo.prototype.getValue = ()=>{
console.log(this.value); // undefined
}
let foo = new Foo()
foo.getValue();
DOM绑定事件时作为事件的回调函数
const button = document.getElementById(‘button‘);
button.addEventListener(‘click‘, ()=>{
console.log(this); // window
this.innerHTML = ‘click-button‘
})
唯一值
// 以往写法 这种写法很容易与其他地方的代码发生冲突
if(obj.bool) {
getValue(obj)
}
obj.bool = true;
// 使用Symbol
let bool = Symbol(‘bool‘);
if(obj[bool]) {
getValue(obj)
}
obj[bool] = true
出现频繁的字符串或者数值
// 普通定义字符串或者数值,不利于后期的代码的维护
const status_pending = ‘pending‘
const status_fulfilled = ‘fulfilled‘
const status_rejected = ‘rejected‘
// Symbol
const status_pending = Symbol()
const status_fulfilled = Symbol()
const status_rejected = Symbol()
私有变量
const Example = (function() {
let name = Symbol(‘name‘);
class Example{
constructor() {
this[name] = ‘name‘
}
getName() {
return this[name];
}
}
return Example
})()
var ex = new Example();
console.log(ex.getName()) // name
console.log(ex.name) // undefined
数组去重
let arr = [1,1,2,2,3,3,4,4,5,5];
console.log([...new Set(arr)]) // [1,2,3,4,5]
标签:ted htm cte 出现 UNC 冲突 避免 get name
原文地址:https://www.cnblogs.com/zhongfang/p/13296587.html