[JavaScript] Uncaught TypeError: Method get Set.prototype.size called on incompatible receiver

在尝试定义一个SingletonSet类,继承自JavaScript的Set并限制其size为1时,遇到错误:'Uncaught TypeError: Method get Set.prototype.size called on incompatible receiver'。问题出在对Set的size属性覆盖上。解决方案是通过Object.assign()来复制方法,避免直接操作导致的错误。修改后的extend函数使得SingletonSet能够正确工作。
摘要由CSDN通过智能技术生成

在对Set进行方法扩展的时候,无法覆盖size属性

情景:定义一个SingletonSet,继承自Set,size只能为1,并且不能add和remove

//首先是extend函数

var extend = (function () {
    //检查是否存在bug
    for (var p in {
            toString: null
        }) {
        //如果进来了,那说明没有bug
        return function extend(o) {
            for (var i = 1; i < arguments.length; i++) {
                var source = arguments[i];
                for (var prop in source) {
                    // var desc = Object.getOwnPropertyDescriptor(source, prop);
                    // Object.defineProperty(o, prop, desc);
                     o[prop] = source[prop];  //书上的例子,
                }
            }
            return o;
        }
    }

    //如果存在bug的话
    return function patched_extend(o) {
        for (var i = 1; i < ar
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值