我正在尝试重用 node.jsBuffer
模块以在其之上创建一个改进的 Buffer 。问题是,如果我直接从它继承,我不能应用构造函数并且一些属性会丢失(因为它们没有被初始化)。上的使用EventEmitter
按预期工作。
恐怕问题出在if(!(this instanceof Buffer)){}
代码上,即评估为假,因为代码实际上并没有从原型继承,所以我需要一种方法来欺骗instanceof
操作员以使其工作。
我正在使用 ES5 类模块https://npmjs.org/package/es5class
var Class = require('es5class');
var MyBuffer = Class.define('MyBuffer').implement(Buffer, true);
// MyBuffer.prototype.write exists
// (new MyBuffer(4)).length is undefined
// (new MyBuffer(4)).parent is undefined, etc
但EventEmitter
照常工作
var Class = require('es5class');
var MyEventEmitter = Class.define('MyEventEmitter').implement(require('events').EventEmitter, true);
// MyEventEmitter.prototype.emit exists
// (new MyEventEmitter())._events is an object as expected
我正在尝试更改 ES5 类模块以使其工作,尝试覆盖constructor
before call f.apply()
,但无济于事。
// $apply is an array of mixin'd classes, for example, Buffer or EventEmitter
self.$apply.forEach(function (f){
var oldctor = instance.constructor; // current instance constructor
Object.defineProperty(instance, 'constructor', {
value : f, // trying to change it
writable : true,
configurable: true,
enumerable : false
});
console.log(instance instanceof f); // false, this needs to evaluate to true just before the f.apply, how to? instance.prototype cannot "redefine" prototype
f.apply(instance, arguments); // works the same as EventEmitter.apply(this, arguments);
Object.defineProperty(instance, 'constructor', {
value : oldctor, // try to restore it
writable : true,
configurable: true,
enumerable : false
});
});
Bergi 在https://github.com/pocesar/ES5-Class/blob/master/index.js#L24中指出,设法用一个相当丑陋的黑客来修复它
superApply = function(instance, object, args){
if (object.$apply.length) {
object.$apply.forEach(function (f){
// dirty little hack to make classes like Buffer think the prototype is instanceof itself
spo(instance, f.prototype);
f.apply(instance, args);
});
}
},