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

functionaFun(){function_(arg){this.arg=arg;}_.prototype.testFun=function(){console.lo... 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(); //可以调用,为啥可以?(我要疯了)
展开
 我来答
suieucn
2018-08-28
知道答主
回答量:14
采纳率:75%
帮助的人:5.3万
展开全部

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

对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(); 调用。

推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式