【问题标题】:How to change the constructor of an object?如何更改对象的构造函数?
【发布时间】:2013-06-16 03:24:59
【问题描述】:

我正在深入研究 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/

【问题讨论】:

标签: javascript object constructor


【解决方案1】:

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/

【讨论】:

  • 刚刚尝试过,但得到的行为与我原来的帖子相同。这是您的更改的小提琴:jsfiddle.net/hammerbrostime/GMFLv
  • @hammerbrostime - 你做错了。更改 constructor 属性不会更改构造函数。改为这样做:jsfiddle.net/GMFLv/1
  • Aadit,感谢您的详细回复。是否有必要创建一个新对象?我想看看我们是否可以更改原始constructorQuestion对象的构造函数,以便我们可以调用新的constructorQuestion()。
  • @hammerbrostime - 不,这是实现您想要实现的目标的唯一方法。
【解决方案2】:

我认为创建具有相同原型的新对象是一样的:

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

newClass.prototype = constructorQuestion.prototype;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 2021-10-22
    相关资源
    最近更新 更多