JavaScript:创建Blob的子类

JavaScript:创建Blob的子类,javascript,inheritance,subclassing,Javascript,Inheritance,Subclassing,我正在试验,看看是否可以自定义一个Blob,并将其传递给文件阅读器。示例代码的目标是能够以编程方式 动态生成数据供FileReader使用。然而,看起来我没有正确地子类化,因为当我尝试使用我的自定义类时,我得到了一个TypeError 以下是我的示例代码: // Example of reading a real blob var realBlob = new Blob(['foo', 'bar']); var reader1 = new FileReader(); reader1.onload

我正在试验,看看是否可以自定义一个Blob,并将其传递给文件阅读器。示例代码的目标是能够以编程方式 动态生成数据供FileReader使用。然而,看起来我没有正确地子类化,因为当我尝试使用我的自定义类时,我得到了一个TypeError

以下是我的示例代码:

// Example of reading a real blob
var realBlob = new Blob(['foo', 'bar']);
var reader1 = new FileReader();
reader1.onload = function(event){
    console.log(JSON.stringify(reader1.result));
};
reader1.readAsText(realBlob);
// Writes "foobar"

// (non-working) streaming blob
function StreamingBlob() {}
StreamingBlob.prototype = new Blob;
StreamingBlob.prototype.constructor = StreamingBlob;
var bInst = new StreamingBlob();

bInst.slice = function (start, end) {
    str = '';
    while (start++ < end) {
        str += 'A';
    }
    return new Blob([str]);
}

// Instance of says it's a Blob
console.log(bInst instanceof StreamingBlob);
console.log(bInst instanceof Blob);

console.log(bInst);
console.log(bInst.slice(1,5));

var reader2 = new FileReader();
reader2.onload = function(event){
    console.log(JSON.stringify(reader2.result));
};
reader2.readAsText(bInst);
// Error!
我很困惑,因为instanceof check声明我的对象是一个Blob,但是readAsText方法生成了一个声明为其他的错误


有更好的方法吗?

如果有,试试。但是我不认为Blob是子类的,它是一个本机接口。看起来这也不起作用,我会看看有没有别的办法得到我想要的。谢谢您可能需要制作一个新的文件读取器,它可以读取您的blob和旧blob,并用它替换旧的blob?还是从头开始实现blob接口的方法?我有一个slice函数,但它说我仍然没有实现blob接口。我最终放弃了它,所以我不知道如何实现它(
true
true
StreamingBlob {slice: function, type: "", size: 0, constructor: function}
Blob {type: "", size: 4, slice: function}
Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.
"foobar"