模块化陷阱
//counter.js
let counter = 10
export default counter;
//index.js
import mycounter from './counter'
mycounter += 1;
console.log(mycounter) //error
因为
mycounter = mycounter + 1;中
第一个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的指向
区别
1.bind需要执行
2.参数不同
arr = [1,2,3]
call(thisObj,arr ) apply(thisObj,...arr )
实战演练
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()
应用
- 1.将伪数组转数组
伪数组类型:
1.dom集合
2.arguments
3.有length属性的对象
let div = document.getElementsByTagName('div');
let arr2 = Array.prototype.slice.call(div)
- arr1.concat(arr2)不会改变原数组
let arr1 = [1],arr2 = [2];
Array.prototype.push.call(arr1,arr2) //[1,[2]]
Array.prototype.push.apply(arr1,arr2) //[1,2]
- 2.判断数据类型
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]'
}
网友评论