请考虑以下代码:
var a = (function()
{
function a(str)
{
if(!(this instanceof a))
return new a(str);
console.log('a created with str: ' + str);
}
a.prototype.b = function()
{
console.log('a.b called');
}
return a;
})();
console.log(a);
a('asd');
a.b();
首先,IIFE的执行使用a
方法prototype
定义类b
。然后return
s类的构造函数,存储在var a
中。这可以通过console.log(a);
在控制台中显示构造函数的代码来证实,而a('asd');
正确地生成了一条说明a created with str: asd
的日志消息。
我不明白为什么线a.b();
导致Uncaught TypeError: a.b is not a function
错误?为什么a.prototype
定义没有延续到var a
?我怎么能在那里得到它?
为什么行a.b();导致未捕获的TypeError:a.b不是函数
这是因为内部函数只在行上执行
a('asd');
但是这一行返回对你从未存储过的new a
实例的引用,因此你无法访问原型方法。
请查看以下修改后的代码段。
var a = (function()
{
function a(str)
{
if(!(this instanceof a))
return new a(str);
console.log('a created with str: ' + str);
}
a.prototype.b = function()
{
console.log('a.b called');
}
return a;
})();
console.log(a);
let c = a('asd'); // Here a holds a reference to inner a and inner a is now called, prototype b added
// a.b(); error, there is no b of (outer) a
c.b(); // This is now OK