扩展内建对象数组
打赏作者

49gd

高产似母猪,对比差距好大啊

JellyBool 回复 49gd

你这个就。。。明天就上传我的视频

eric2100

英文發音好標準耶,而且好像學習效率提高了。

laland 回复 eric2100

你确定选对标准了吗? -_-!

Osub

生一堆猴子录视频,效率会更高,很期待

zhangsan

定义的 add 方法,调用的是 push 方法…

为什么把 push 改回 add 会报方法不存在?

class PersonCollection extends Array {
    
    constructor(name, ...items) {
        super(...items);
        this.name = name;
    }

    add(item) {
        this.push(item);
    }
}
    
const collection = new PersonCollection('name', 
    {'name': 'zhangsan'},
    {'name': 'lisi'}
);

collection.add({'name': 'wangwu'});
console.log(collection);

//Uncaught TypeError: collection.add is not a function
Yawenina 回复 zhangsan

我直接复制你的代码是可以运行的…

gaoyuan1223m 回复 Yawenina

我也有一样的问题,说add 和topRated 不是function

acheng93

很好,不仅分享代码还分享经典电影,给个?😃

thirdriver
    function MyArray() {
        return Array.apply(this, arguments);
    }

    const colors = new MyArray();
    colors[0] = "red";

    console.log(colors.length);
    colors.length = 0;
    console.log(colors[0]);

可以得到想要的结果

laland 回复 thirdriver

视频内容中MyArray是没写return的,作构造函数时默认返回的是新建的对象,里面的this指的是新建的对象,意图是使新建的对象也拥有数组的属性和方法,不过显然是不成功的.
你这里加上return后返回的是数组的实例(既然是数组,当然就有length属性,所以才有已经得到想要结果的错觉),而不是前面提到的构造函数新建的对象,相应地也就没有新建对象(this)的属性和方法