Javascript Js通过原型从类继承
我需要继承对象来创建我自己的Javascript Js通过原型从类继承,javascript,inheritance,prototype,Javascript,Inheritance,Prototype,我需要继承对象来创建我自己的类型,并添加其他方法等。但我有点困惑如何以正确的方式做到这一点。我试着这样做: var CFDataView = function() { this.offset = 0; }; CFDataView.prototype.__proto__ = DataView.prototype; CFDataView.prototype.readU8 = function() { if (this.byteLength >= this.offset+1)
类型
,并添加其他方法等。但我有点困惑如何以正确的方式做到这一点。我试着这样做:
var CFDataView = function() {
this.offset = 0;
};
CFDataView.prototype.__proto__ = DataView.prototype;
CFDataView.prototype.readU8 = function() {
if (this.byteLength >= this.offset+1) {
return this.getUint8(this.offset++);
} else {
return null;
}
};
var CFDataView = function CFDataView(buffer, byteOffset, byteLength) {
DataView.call(this, buffer, byteOffset, byteLength);
this.offset = 0;
};
CFDataView.prototype = Object.create(DataView.prototype);
CFDataView.prototype.constructor = CFDataView;
但有一个错误:
DataView.prototype.ByTeleLength在不兼容的接收器CFDataView上调用
从提案中,我尝试这样做:
var CFDataView = function() {
this.offset = 0;
};
CFDataView.prototype.__proto__ = DataView.prototype;
CFDataView.prototype.readU8 = function() {
if (this.byteLength >= this.offset+1) {
return this.getUint8(this.offset++);
} else {
return null;
}
};
var CFDataView = function CFDataView(buffer, byteOffset, byteLength) {
DataView.call(this, buffer, byteOffset, byteLength);
this.offset = 0;
};
CFDataView.prototype = Object.create(DataView.prototype);
CFDataView.prototype.constructor = CFDataView;
但收到一个错误:
TypeError:构造函数DataView需要“新建”
您需要使用ES6
class
来扩展本机类,例如DataView
。正如错误消息所说,您只能在真实数据视图(“兼容接收器”)上使用这些方法,要创建这些方法,您需要使用DataView
构造函数(使用new
-或super
或Reflect.construct
)。所以