成长(14/2000)——面试题合集11

2021-06-17  本文已影响0人  Kiki_Q

模块化陷阱

//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()

应用

let div = document.getElementsByTagName('div');
let arr2 = Array.prototype.slice.call(div)

let arr1 = [1],arr2 = [2];
Array.prototype.push.call(arr1,arr2) //[1,[2]]
Array.prototype.push.apply(arr1,arr2) //[1,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]'

}
上一篇下一篇

猜你喜欢

热点阅读