如何更改对象的构造函数? [英] How to change the constructor of an object?

查看:123
本文介绍了如何更改对象的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将更深入地研究Javascript,并学习构造函数方法的工作原理。

I am diving deeper into Javascript, and learning how constructor methods work.

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

In the code below, I would expect that I would be able to overwrite the constructor of an object, so that newly created instances would use the new constructor. However, I can't seem to make new instances use a new constructor.

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

Any insight as to what is going on would be greatly appreciated!

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/

推荐答案

构造函数是函数原型的属性,而不是函数本身。做:

The constructor is a property of the prototype of the function, not the function itself. Do:

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

有关更多信息,请参见: https://stackoverflow.com/a/8096017/783743

For more information see: https://stackoverflow.com/a/8096017/783743

顺便说一句,如果您希望代码 howComeConstructorHasNotChanged = new constructorQuestion(); 提醒新构造函数 不会发生这是因为您没有调用新的构造函数,而是调用了旧的构造函数。您想要的是:

BTW, if you expect the code howComeConstructorHasNotChanged = new constructorQuestion(); to alert "new constructor" that won't happen. This is because you're not calling the new constructor, you're calling the old one. What you want is:

howComeConstructorHasNotChanged = new constructorQuestion.prototype.constructor;

更改构造函数属性并不神奇更改构造函数。

Changing the constructor property doesn't magically change the 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/

This will work. See: http://jsfiddle.net/GMFLv/1/

这篇关于如何更改对象的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆