javascript – this.constructor.prototype – 不能完全覆盖,但可以写个别道具吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – this.constructor.prototype – 不能完全覆盖,但可以写个别道具吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2137字,纯文字阅读大概需要4分钟。
内容图文
![javascript – this.constructor.prototype – 不能完全覆盖,但可以写个别道具吗?](/upload/InfoBanner/zyjiaocheng/714/4d63dfd0bcbd43bd88d3dfa0f05bbb3e.jpg)
TL; DR?为什么我不能在构造函数中覆盖构造函数的原型?
我正在弄清楚我的原型继承模式.我不喜欢原型通常是从??构造函数外部定义的,并希望逻辑上更好地封装事物.
我发现我期望工作的一条神奇的线路没有.
function Orifice(){
this.exhaust=function(){};
this.ingest=function(){};
}
var standardOrifice = new Orifice();
function Sphincter(){
this.constructor.prototype = standardOrifice; // <-- does not work
this.relax=function(){};
this.tighten=function(){};
}
有趣的是,我可以为this.constructor.prototype编写单独的属性,但是我不能以与构造函数定义之外的方式相同的方式覆盖整个原型对象.
所以像这样的东西工作:
this.constructor.prototype.exhaust = standardOrifice.exhaust;
this.constructor.prototype.ingest = standardOrifice.ingest;
为此,我可以创建一个简单的克隆函数来处理:
function extend(target){
return {
from: function(obj){
target.__proto__ = obj.constructor.prototype;
for (key in obj) if (obj.hasOwnProperty(key)) target[key]=obj[key];
return target;
}
};
}
值得庆幸的是,到目前为止,在我的测试中,这种技术似乎运行良好,但我不确定是否存在我可能遗漏的细节或性能案例.
function Sphincter(){
extend(this.constructor.prototype).from(standardOrifice);
//...
}
为什么我不能在构造函数中覆盖构造函数的原型?但我可以在构造函数之外?单独编写属性是否在构造函数中起作用?
解决方法:
Why can’t I overwrite a constructor’s prototype from within the constructor?
你可以,但为时已晚.新实例已经生成,继承自旧原型.也许阅读how new works.
I don’t like how prototypes are usually defined externally from a constructor.
就是那样子.你真的不应该在构造函数中设置原型 – 它会在每次创建新实例时执行.这就是原型不应该是什么.另见Assigning prototype methods *inside* the constructor function – why not?
and want to logically encapsulate things better.
你可能想看看各种(揭示)module patterns.或者甚至可能在一些类框架中.
I’m currently looking for more concrete reasons that I should not go forth with the pattern I’ve been presenting.
它在Internet Explorer中不起作用.它不适用于任何不支持__proto__属性的ES5兼容环境.你永远不应该使用它在现有对象上设置原型.相反,使用Object.create(或其垫片)作为Correct javascript inheritance – 这要求您在构造函数之外覆盖原型.
我的建议是在构造函数之外调用你的扩展助手,它仍然有一个很好的语法.
内容总结
以上是互联网集市为您收集整理的javascript – this.constructor.prototype – 不能完全覆盖,但可以写个别道具吗?全部内容,希望文章能够帮你解决javascript – this.constructor.prototype – 不能完全覆盖,但可以写个别道具吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。