javascript中constructor指向问题

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

function Fruit(){ }
var f=new Fruit();
console.log(f.constructor);//打印出Fruit()

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

function Fruit(){ this.name="水果"}
//var f=new Fruit();
function Apple(){this.name="苹果";}
Apple.prototype=new Fruit();
var apple=new Apple();
console.log(apple.constructor);//依然打印出Fruit()
Apple.prototype={};//空对象的构造器是Object()
apple=new Apple();
console.log(apple.constructor);//指向Object()

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

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

   apple.constructor==Apple.prototype.constructor

var apple2=new apple.constructor();
console.log(apple2.name);

或者

var apple2=new Apple.prototype.constructor();
console.log(apple2.name);

打印的都是水果。

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

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

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

Apple.prototype.constructor=Apple;

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

 apple.constructor=Apple;

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

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

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

原文地址:https://www.cnblogs.com/guoyansi19900907/p/12089151.html