gpt4 book ai didi

javascript - 如何更改对象的构造函数?

转载 作者:行者123 更新时间:2023-11-30 07:41:01 25 4
gpt4 key购买 nike

我正在深入研究 Javascript,并学习构造方法的工作原理。

在下面的代码中,我希望能够覆盖对象的构造函数,以便新创建的实例可以使用新的构造函数。但是,我似乎无法让新实例使用新的构造函数。

任何有关正在发生的事情的见解都将不胜感激!

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

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

这是 fiddle :http://jsfiddle.net/hammerbrostime/6nxSW/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/

关于javascript - 如何更改对象的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17193861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com