为IIFE中的类定义原型函数,同时强制“新”

问题描述 投票:-1回答:1

请考虑以下代码:

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。然后returns类的构造函数,存储在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?我怎么能在那里得到它?

javascript function class oop object
1个回答
1
投票

为什么行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
© www.soinside.com 2019 - 2024. All rights reserved.