为了账号安全,请及时绑定邮箱和手机立即绑定

javascript 函数返回值的问题,请高手解答

javascript 函数返回值的问题,请高手解答

开心每一天1111 2018-08-05 05:05:17
function aFun(){function _(arg){this.arg = arg;}_.prototype.testFun = function(){console.log('this is prototype testFun')};_.testFun2 = function(){console.log('this is testFunc2');}return _;};var afun = new aFun('123');console.log(object)afun.testFun2(); //可以调用//afun.testFun(); //不是在原型链上么?,为啥不可以调用???,var aFun2 = (function (){function _(arg){this.arg = arg;}_.prototype.testFun = function(){console.log('this is prototype testFun')};_.testFun2 = function(){console.log('this is testFunc2');}return _;})();var afun2 = new aFun2('ddd');console.log(afun2 instanceof aFun2)//afun2.testFun2(); //不可以调用,为啥?afun2.testFun(); //可以调用,为啥可以?
查看完整描述

1 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

详细解释之前,你必须了解类实例化的过程中,都经历了什么。

对Function实例化,Function相当于是构造器。

  • 当实例化时,解释器先生成一个新的对象(Object),此对象的原型链上有一个constructor属性,指向这个构造器(Function)本身

  • 将这个对象作为构造器的上下文(this)传入构造器函数(Function),并执行构造器函数

  • 根据构造器函数最终返回的结果,如果是对象(Object),则使用返回的对象为实例化的对象;否则,使用之前构造时的上下文对象(this)作为实例化的对象

明白了这一点再看第一段代码。当 new aFun 时,执行 aFun 构造器函数,因为返回值是 _ 这个对象,所以以它作为实例化的结果。因此,此对象上的 testFun2 方法可以直接调用,但 testFun 因为在 prototype 属性中,所以无法直接调用。

第二段代码使用了闭包。当定义完 aFun2 时,aFun2 的结果就是 _ 这个函数。然后对 new aFun2 就相当于 new _(只不过作用域不同了)。由于 _ 函数并没有返回结果,所以实例化的结果就是以 _ 为构造器的对象,而此时 _ 的 prototype 属性也因为实例化,新对象的原型链将指向它。因此,只能调用原型链上的 testFun 方法,却不能调用 testFun2 方法。

第一段代码仍能通过 afun.prototype.testFun(); 调用;第二段代码仍能通过 afun2.constructor.testFun2(); 调用。


查看完整回答
反对 回复 2018-09-01
  • 1 回答
  • 0 关注
  • 585 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信