10. 重写原型对象上的方法

10. 重写原型对象上的方法

实现方式:

  1. 覆盖原方法:

    1. 问题:污染了全局的原方法,不推荐
  2. 重新创建一个原型对象。并且该原型对象的隐式原型指向原原型对象

    1. var obj1 = Object.create(obj2)

      console.log(obj1.\_\_proto\_\_ === obj2.prototype)

    2. 如何调用原方法:

      apply(this, arguments)

      Array.prototype.push.apply(this,arguments);
      
    3. 如何调用自建的原型对象上的方法

      修改隐式原型

      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)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值