在内置类的原型上,封装方法
- 在内置类原型上的方法,类所对应的实例可以直接调取使用,例如:实例.方法() ary.push()
- 如果我们也把自己写的方法放到原型上,那么当前类的实例也可以直接这样调取使用了很方便
- 需要注意:
1.自己扩展的方法不能影响原有内置的方法(我们自己设置的方法最好加前缀:my)
2.扩展方法中的this一般都是当前类的实例(也就是要操作的值):实例.方法()
1、检测某个属性是否为对象的公有属性
Object.prototype.hasPubProperty = function(property) {
//=>验证传递的属性名合法性(一般只能是数字或字符串等基本值)
if(!["string","number","boolean"].includes(typeof property)) return false;
//=>开始校验是否为公有属性(方法中的this就是要校验的对象)
let n = property in this;
let m = this.hasOwnProperty(property);
return n && !m;
}
console.log(Array.prototype.hasPubProperty('push')); //=>false
console.log([].hasPubProperty('push')); //=>true
2、数组去重
Array.prototype.myUnique = function() {
//=> 使用ES6 Set进行数组去重
let set = new Set(this);
//=> [...set]类数组转数组,也可以是用Array.from(set)转数组
return [...set];
}
let ary = [12,3,44,55,55,66,66];
console.log(ary.myUnique()); //=>[12, 3, 44, 55, 66]
3、数组去重后排序
Array.prototype.myUniqueSort = function() {
let set = new Set(this);
//=> 链式调用(保证当前方法执行完返回的结果依然是Array类的实例)
return [...set].sort((a, b) => a - b );
}
let ary = [12, 3, 44, 55, 55, 66, 66, 0];
console.log(ary.myUniqueSort()); //=>[0, 3, 12, 44, 55, 66]