私は古いES5コードベースからいくつかのコードをリファクタリングしています。そこでは次のことを行っていました。
function ObjectCreatorFunction() {
this.someProperty= {};
}
/*
* Static method, to extend the object passed as a parameter with the
* ObjectCreatorFunction instance properties and methods
*/
ObjectCreatorFunction.extend = function extend(object) {
var key;
ObjectCreatorFunction.call(object);
for (key in ObjectCreatorFunction.prototype) {
if (ObjectCreatorFunction.prototype.hasOwnProperty(key)) {
if (!object.hasOwnProperty(key)) {
object[key] = ObjectCreatorFunction.prototype[key];
}
}
}
return object;
};
ObjectCreatorFunction.prototype.someMethod = function someMethod() {...}
//etc
私はES6の書き換えで同じことをしようとしているので、これを持っています
class ClassName{
constructor() {
this.someProperty= {};
}
static extend(object) {
let key;
ClassName.constructor.call(object);
for (key in ClassName.prototype) {
if (ClassName.prototype.hasOwnProperty(key)) {
if (!object.hasOwnProperty(key)) {
object[key] = ClassName.prototype[key];
}
}
}
return object;
}
someMethod() {...}
//etc
}
私の問題は、行ClassName.constructor.call(object);
が意図したとおりに機能しないことです。つまり、渡されたオブジェクトがクラスのインスタンスプロパティを取得しません。
私はこれを(いくつかの非正統的なものでさえ)書き直して役に立たないようにするいくつかの方法を試みました。
ES6を使用して、クラスのインスタンスプロパティでオブジェクトを拡張するにはどうすればよいですか?
免責事項:
私のコードは、babelとwebpackを使用してトランスパイルプロセスを通過します。クラスが内部でどのように機能するかに影響がある場合。
いいえ、これはclass
構文では機能しません。それは単なる構文糖衣以上のものです。プロトタイプの継承は同じままでしたが、インスタンスの初期化は、特に継承されたクラスの場合、動作が異なるようになりnew
ました。新しいインスタンスを作成しないと、コンストラクターを呼び出すことはできません。
私はあなたのミックスインについて明確にし、それにinit
方法を与えることをお勧めします:
class Mixin {
constructor(methods) {
this.descriptors = Object.getOwnPrpertyDescriptors(methods);
}
extend(object) {
for (const p of this.descriptors)) {
if (Object.prototype.hasOwnProperty.call(o, p)) {
if (process.env.NODE_ENV !== 'production') {
console.warn(`Object already has property "${p}"`);
}
} else {
Object.defineProperty(o, p, this.descriptors[p]);
}
}
}
}
// define a mixin:
const xy = new Mixin({
initXY() {
this.someProperty= {};
},
someMethod() { … }
});
// and use it:
class ClassName {
constructor() {
this.initXY();
}
}
xy.extend(ClassName.prototype);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加