文章目錄
1 前言
這篇是根據掘金小冊來寫的,覆蓋不一定全面,但是在前端進階上有幫助。如有錯誤,歡迎指正。參考鏈接 https://yuchengkai.cn/docs/frontend/
2 new
2.1 調用new的過程
1 新生成了一個對象
2 鏈接到原型
3 綁定this
4 返回新對象
2.2 如何實現new
參考鏈接 https://github.com/mqyqingfeng/Blog/issues/13
function create() {
//1 創建空對象
var obj = new Object()
//2 鏈接到原型
//2.1 傳入參數第一個就是構造函數 即arguments[0] 同時後面傳參需要去掉函數 所以用shift方法
Con = [].shift.call(arguments)
//2.2 真正鏈接到原型
obj.__proto__ = Con.prototype
//3 綁定this
let res = Con.apply(obj, arguments)
return typeof res === 'object' ? res : obj
}
function Person(name) {
this.name = name
}
console.log(create(Person, 'ljs'))
輸出爲Person{name:‘ljs’}
最後一步的判斷是必要的,否則沒有返回值的情況下會返回undefined。如果返回對象不包括所有屬性,或者返回的是基本類型值,也會有問題。
3 深淺拷貝
參考鏈接 https://juejin.im/post/59ac1c4ef265da248e75892b
深淺拷貝是針對引用類型而言的,基本類型值不可變。淺拷貝和賦值也是有區別的。
淺拷貝將A對象複製到B對象中,不包括B對象中的子對象。
深拷貝將A對象複製到B對象中,包括B對象中的子對象。
3.1 如何實現深淺拷貝
淺拷貝:
(1) let b=Object.assign({},a)
(2) let b={…a}
(3) for (var prop in src) {
if (src.hasOwnProperty(prop)) {
dst[prop] = src[prop];
}
}
深拷貝:
(1) JSON.parse(JSON.stringify(object)) 會忽略undefined和symbol,不能序列化函數,不能解決循環引用的對象
(2) jQuery的extend方法
4 防抖節流
之前的文章總結過 https://blog.csdn.net/ChristineAS/article/details/95454485#36__449
防抖 多個動作合併爲一個動作
function debounce(fn,wait){
let timeout=null;
return function(){
if(timeout){
clearTimeout(timeout)
}
timeout=setTimeout(fn,wait)
}
}
function hanlde(){
console.log('debounce')
}
window.addEventListener('scroll',debounce(hanlde,1000))
節流 每隔一定時間執行一個動作
function throttle(fn, wait) {
var prev = Date.now()
return function() {
var now = Date.now()
if (now - prev > wait) {
fn()
prev = Date.now()
}
}
}
function handle() {
console.log('throttle')
}
window.addEventListener('scroll', throttle(hanlde, 1000))
5 clientHeight、offsetHeight、scrollHeight
參考 https://github.com/pramper/Blog/issues/10
clientHeight 可視區域高度 包括padding,不包括border、margin、滾動條
offsetHeight 元素本身高度 包括padding,border,滾動條
scrollHeight 元素內容整體高度 包括padding,不包括border、margin
scrollTop 滾動的高度
offsetTop 相對於最近的position不爲static的父元素的上偏移距離,沒有則指向body
6 JS實現拖拽效果
JS原生
參考 https://x-front-team.github.io/2017/03/01/js%E5%AE%9E%E7%8E%B0%E6%8B%96%E6%8B%BD%E6%95%88%E6%9E%9C/
主要使用clientX、offsetLeft、dragCircle.style.left
H5 drag&drop API
參考 https://www.w3school.com.cn/tiy/t.asp?f=html5_draganddrop
draggable=true
οndragstart=drag(event)
event.dataTransfer.setData(‘XXX’,‘XXX’)
οndrοp=drop(event)
event.dataTransfer.getData(‘XXX’)
event.target.appendChild()