1

私は Javascript を深く掘り下げ、コンストラクター メソッドがどのように機能するかを学んでいます。

以下のコードでは、新しく作成されたインスタンスが新しいコンストラクターを使用するように、オブジェクトのコンストラクターを上書きできると期待しています。ただし、新しいインスタンスに新しいコンストラクターを使用させることはできないようです。

何が起こっているのかについての洞察は大歓迎です!

function constructorQuestion() {
    alert("this is the original constructor");
};

c = new constructorQuestion();
constructorQuestion.constructor = function() { alert("new constructor");}
howComeConstructorHasNotChanged = new constructorQuestion();

これがフィドルです:http://jsfiddle.net/hammerbrostime/6nxSW/1/

4

2 に答える 2

6

は、関数自体ではなく、関数のconstructorプロパティです。prototype行う:

constructorQuestion.prototype.constructor = function() {
    alert("new constructor");
}

詳細については、https ://stackoverflow.com/a/8096017/783743 を参照してください。


howComeConstructorHasNotChanged = new constructorQuestion();ところで、コードが警告を発すると予想される場合は、"new constructor"それは発生しません。これは、新しいコンストラクターを呼び出しているのではなく、古いコンストラクターを呼び出しているためです。あなたが望むものは:

howComeConstructorHasNotChanged = new constructorQuestion.prototype.constructor;

プロパティを変更constructorしても、魔法のようにコンストラクターが変更されるわけではありません。

あなたが本当に欲しいのは:

function constructorQuestion() {
    alert("this is the original constructor");
};

c = new constructorQuestion();

function newConstructor() {
    alert("new constructor");
}

newConstructor.prototype = constructorQuestion.prototype;

howComeConstructorHasNotChanged = new newConstructor();

これは機能します。参照: http://jsfiddle.net/GMFLv/1/

于 2013-06-19T14:27:08.623 に答える
1

次のように、同じプロトタイプで新しいオブジェクトを作成するのも同じだと思います。

function newClass(){
    alert('new class with same prototype');
}

newClass.prototype = constructorQuestion.prototype;
于 2013-06-19T14:27:26.167 に答える