在JavaScript中更改构造函数 [英] Changing constructor in JavaScript
本文介绍了在JavaScript中更改构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试一段时间来切换对象的构造函数而我失败了。继续代码将显示我需要的示例。谢谢。
I am trying for a while to switch constructor for a object and I am failing. Continuing code will show example of what I need. Thanks.
<script type="text/javascript">
function Me(){
this.name = "Dejan";
}
function You(){
this.name = "Ivan";
}
Me.prototype.constructor = You;
somebody = new Me();
alert(somebody.name); // **It gives Dejan, and I am expecting Ivan**
</script>
推荐答案
您无法更改对象的构造函数,然而,您可以更改构造函数返回的对象的类型,如(在您的示例中)
You can't change the constructors of an object, you can however change the 'type' of the object the constructor returns, with (as in your example)
Me.prototype = new You();
这将导致新的Me()从对象You继承。然而,Me()函数中的this.name将掩盖从你继承的那个,所以做这样的事情:
which would cause new Me()'s to inherit from the object You. However this.name in the Me() function will overshadow the one inherited from you so do something like this:
function Me(){
this.name = this.name || "Dejan";
}
function You(){
this.name = this.name || "Ivan";
}
Me.prototype = new You();
somebody = new Me();
alert(somebody.name);
这篇关于在JavaScript中更改构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文