美文网首页
constructor修订问题

constructor修订问题

作者: MakingChoice | 来源:发表于2016-10-14 19:55 被阅读13次

在模拟javascrpt类的时候需要的一项工作就是construtor重新修订问题,下面简要说一下。

//说明一下constructor作用
function C(){};
function P(){};
C.prototype=P.prototype;//把C的原型指向了P的原型
C.prototype.constructor;// function P(){}  C函数的原型的constructor是P函数。这里是原型链的内容,即C的prototype上有一个constructor属性,本来是指向C函数的。但是当C.prototype=P.prototype时,就指向了P。

其实construtor的作用就是重写原型链,方式继承的时候原型链更改到别的函数上。下面是一个例子

//父类
function Parent(){};
Parent.prototype.eating=function(){console.log("eat")};
Parent.prototype.driking=function (){console.log("drinking")};
//子类
function Children(){};
Children.prototype.playing=function(){console.log("playing")};
Children.prototype=Parent.prototype;
var children=new Children();
children.playing;//undefined

上面的代码中,没有重新修订Children函数的原型指向,所以当重新调用chilren.playing的时候,就无法通过原型链查找到对应的方法。

下面的代码是经过修订后的,就可以获取原型链上对应的方法

//父类
function Parent(){};
Parent.prototype.eating=function(){console.log("eat")};
Parent.prototype.driking=function (){console.log("drinking")};
//子类
function Children(){};
Children.prototype=Parent.prototype;
//一定要先重新修订contructor的指定,然后在在原型链prototype上挂函数。
Children.prototype.constructor=Children;
Children.prototype.playing=function(){console.log("playing")};
var children=new Children();
children.playing;//playing

最后总结一下就是,先父类===》》再子类===》》再继承父类===》》重新修订子类constructor===》》在子类原型挂接方法

相关文章

  • constructor修订问题

    在模拟javascrpt类的时候需要的一项工作就是construtor重新修订问题,下面简要说一下。 其实cons...

  • *** is not a constructor之命名不规范引来

    一、问题现象 :MessageBriefPage is not a constructor 二、问题原因:类名和下...

  • react 入门(2)

    constructor JSX中的html解析问题 dangerouslySetInnerHTML htmlFo...

  • string

    2019.3.8 问题: 答案: fill constructor如下:string(size_t n, char...

  • constructor()

    constructor里的this.state和直接写this.state区别?答案:没有区别 在React中co...

  • constructor

    constructor 为什么x会有constructor属性。因为每一个构造函数原型都会生成constructo...

  • constructor

    constructor 翻译:构造者、构造器语法:object.constructor 输出:function e...

  • constructor

    所有的函数都有一个prototype属性,它是一个对象。 prototype有一个constructor的属性,默...

  • Constructor

    this:继承同一类中的其它构造函数 Class Car{private string _description;...

  • constructor()

    constructor()是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constru...

网友评论

      本文标题:constructor修订问题

      本文链接:https://www.haomeiwen.com/subject/hxhnyttx.html