web前端:javascript中constructor指向问题

    作者:思思博士更新于: 2020-03-23 20:40:02

    Web开发

      构造函数(Constructor)在对象创建或者实例化时候被调用的方法。通常使用该方法来初始化数据成员和所需资源。构造器Constructor在js不能被继承,因此不能重写Overriding,但可以被重载Overloading。

      首先用一个例子指出来constructor存在形式。

      functionFruit(){}

      varf=newFruit();

      console.log(f.constructor);//打印出Fruit()

      由上面的代码我们总结出结论1:上面的代码在控制台可以看出constructor是指向构造器Fruit的引用。

      functionFruit(){this.name="水果"}

      //varf=newFruit();

      functionApple(){this.name="苹果";}

      Apple.prototype=newFruit();

      varapple=newApple();

      console.log(apple.constructor);//依然打印出Fruit()

      Apple.prototype={};//空对象的构造器是Object()

      apple=newApple();

      console.log(apple.constructor);//指向Object()

      这个地方就有点奇怪了。这个constructor到底指向的是那个实例的构造器?

      根据上面的代码总结出结论2:constructor指向的是原型对象的构造器的引用

      即apple.constructor==Apple.prototype.constructor

      varapple2=newapple.constructor();

      console.log(apple2.name);

      或者

      varapple2=newApple.prototype.constructor();

      console.log(apple2.name);

      打印的都是水果。

      我们现在想让他执行的是苹果的打印;这个时候就需要对constructor的指向进行重新指定。

      根据上面的两个结论:无论是修改实例的constructor还是构造器的原型constructor属性都是可以达到目的的;

      可以在重写了prototype属性的代码后写下这样的代码

      Apple.prototype.constructor=Apple;

      或者在实例化后对实例的constructor进行重新制定。

      apple.constructor=Apple;

      虽然上面的两种方式都能达到目的,但是推荐使用第一种。

      第二种方式需要有一个实例化的对象,而我们只用在对继承的创建完成后才会去实例化,

      等有了实例化对象在去修改constructor,这个时候已经迟了,意义已经不大了,继承的关系已经确定了。

      构造函数在C++中如果写成public属性那么可以继承。

课课家教育

未登录