操作js原型链的遇到坑

79 阅读1分钟

在为公司封装前端开发框架时,为开发,减少代码量。通常会封装一些功能性的函数,增强js的功能。例如,一般判断数组为空时。我们一般都是arr.length===0,更进一步是直接在在原型链上添加。

Array.prototype.isEmpty = function (){
let arr = this;
return arr.length ===0
}

let arr = [12,2,3,4];
console.log(arr.isEmpty())

但是这样会有些许风险,这样直接添加,会被for--in--便利出来,如果有同事使用for--in遍历数组(不推荐),超出预定的属性,会给他们造成困惑。

for(let i in arr){
console.log(i)
}

> 0
> 1
> 2
> 3
> isEmpty

这里推荐Object.defineProperty,里面的enumerable可以自定义属性是否能被便利出来。 具体如下

const isEmpty =function(){
let arr = this;
return arr.length ===0
}
Object.defineProperty(Array.prototype,'isEmpty',{
value:isEmpty,
configurable:false, //对象的属性是否可以被删除
writable:false,
enumerable:false //对象的属性是否可以被遍历
})

let arr = [12,2,3,4];
console.log(arr.isEmpty()) // false

这样既能自己添加额外功能,也不会被for--in遍历出来。

for(let i in arr){
console.log(i)
}

> 0
> 1
> 2
> 3