10. 重写原型对象上的方法
实现方式:
覆盖原方法:
- 问题:污染了全局的原方法,不推荐
重新创建一个原型对象。并且该原型对象的隐式原型指向原原型对象
var obj1 = Object.create(obj2)
console.log(obj1.\_\_proto\_\_ === obj2.prototype)
如何调用原方法:
apply(this, arguments)
Array.prototype.push.apply(this,arguments);
如何调用自建的原型对象上的方法
修改隐式原型
arr.__proto__ = newPrototype;
10-1. 直接修改原数组的方法
// 错误:引用地址相同,导致originPrototype.push 和Array.prototype.push是一个push,形成递归调用,内存溢出
// var originPrototype = Array.prototype;
// originPrototype.push = function(){
// Array.prototype.push.apply(this,arguments);
// }
// 创建一个新的push方法
var originPush = Array.prototype.push;// 缓存原数组的方法
// 直接修改原型上的方法,会导致数组的方法被全局污染了。
Array.prototype.push = function(){
console.log(this);// arr.push,所以this是arr
// 1. 调用原数组方法
originPush.apply(this,arguments);
// 2. 输出视图更新
console.log('视图更新');
}
var arr = [1,2,3,4];
arr.push(5,6);
console.log(arr);
//
arr.push(123,33,5,7,4)
10-2. 自建原型对象修改方法
// 1. 创建新的数组原型对象
var newPrototype = Object.create(Array.prototype);
console.log(newPrototype); // {}
// 2. 在自建的原型对象上写方法
newPrototype.push = function(){
// 1. 调用原数组的push方法
Array.prototype.push.apply(this,arguments);
// 2. 视图更新
console.log('视图更新');
// 3. 返回新数组的长度
return this.length;
}
var arr = [1,2,3,4];
if(arr instanceof Array){
arr.__proto__ = newPrototype
}
arr.push(5);
10-3. 以上两种方式代码内存图示
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JPZVFl8h-1681398026395)(js%E5%9F%BA%E7%A1%80.assets/%E9%87%8D%E5%86%99%E5%8E%9F%E5%9E%8B%E6%96%B9%E6%B3%95.png)]