首页 > 编程语言 > 详细

javascript中constructor指向问题

时间:2019-12-24 00:55:59      阅读:81      评论:0      收藏:0      [点我收藏+]

首先用一个例子指出来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;

 

javascript中constructor指向问题

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!