模塊化陷阱
//counter.js
let counter = 10
export default counter;
//index.js
import mycounter from './counter'
mycounter += 1;
console.log(mycounter) //error
因?yàn)?mycounter = mycounter + 1;中
第一個(gè)mycouner在此文件中未定義
const person = {
name:'lydia'
}
Object.defineProperty(person, 'age', { value: 21 })
console.log(person)
console.log(Object.keys(person));
//{ name: 'lydia' }
//[ 'name' ]
call皮钠、bind和apply
作用
改變this的指向
區(qū)別
1.bind需要執(zhí)行
2.參數(shù)不同
arr = [1,2,3]
call(thisObj制跟,arr ) apply(thisObj我注,...arr )
實(shí)戰(zhàn)演練
let obj = {
name:'dq'
}
function Child(name){
this.name = name
}
Child.prototype = {
constructor : Child,
showName: function ( ) {
console.log(this.name)
}
}
let child = new Child('xz');
child.showName();
child.showName.call(obj);
child.showName.apply(obj);
let bind = child.showName.bind(obj)
bind()
應(yīng)用
- 1.將偽數(shù)組轉(zhuǎn)數(shù)組
偽數(shù)組類(lèi)型:
1.dom集合
2.arguments
3.有l(wèi)ength屬性的對(duì)象
let div = document.getElementsByTagName('div');
let arr2 = Array.prototype.slice.call(div)
- arr1.concat(arr2)不會(huì)改變?cè)瓟?shù)組
let arr1 = [1],arr2 = [2];
Array.prototype.push.call(arr1,arr2) //[1,[2]]
Array.prototype.push.apply(arr1,arr2) //[1,2]
- 2.判斷數(shù)據(jù)類(lèi)型
let array1 = [1,2,3];
function isArray(array) {
return Object.prototype.toString.call(array) === '[object Array]'
// return Object.prototype.toString.call(array) === '[object Object]'
// return Object.prototype.toString.call(array) === '[object String]'
// return Object.prototype.toString.call(array) === '[object Null]'
}