javascript中constructor指向问题

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

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

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

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到底指向的是那个实例的构造器?this

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

   apple.constructor==Apple.prototype.constructorprototype

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

或者code

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

打印的都是水果。对象

咱们如今想让他执行的是苹果的打印;这个时候就须要对constructor的指向进行从新指定。blog

根据上面的两个结论:不管是修改实例的constructor仍是构造器的原型constructor属性都是能够达到目的的继承

能够在重写了prototype属性的代码后写下这样的代码原型

Apple.prototype.constructor=Apple;

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

 apple.constructor=Apple;

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

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

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

相关文章
相关标签/搜索