构造函数原型模式创建类调用原型方法报TypeError错误求助
问题分析与解决:TypeError: this.initializeSieve is not a function
你碰到的这个错误根源很明确——你用箭头函数定义原型方法导致了this指向异常。
箭头函数的特性是不会绑定自身的this,它会继承外层作用域的this值。当你通过primeGenerator.generatePrimeNumbers(100)调用方法时,generatePrimeNumbers作为箭头函数,内部的this并不会指向primeGenerator这个实例,而是指向外层的全局对象(浏览器环境是window,Node.js环境是global)。全局对象上当然没有initializeSieve方法,所以就抛出了TypeError。
解决方法很简单,把原型里的箭头函数改成普通函数声明,这样函数内部的this就会正确指向调用它的PrimeGenerator实例:
function PrimeGenerator() { this.s = 0; this.f = []; this.primes = []; } PrimeGenerator.prototype = { constructor: PrimeGenerator, generatePrimeNumbers: function(maxValue) { if (maxValue < 2) { return []; // 对不合理值返回空数组 } else { this.initializeSieve(maxValue); // this.sieve(); // this.loadPrimes(); return this.primes; } }, initializeSieve: function(maxValue) { this.s = maxValue + 1; this.f = []; let i; // 将数组初始化为true for (i = 0; i < this.s; i++) { this.f[i] = true; } // 去掉已知的非素数 this.f[0] = this.f[1] = false; } }; const primeGenerator = new PrimeGenerator(); const centArr = primeGenerator.generatePrimeNumbers(100); console.log(centArr);
如果你习惯ES6的写法,也可以用对象方法的简写形式(同样是普通函数,不是箭头函数):
function PrimeGenerator() { this.s = 0; this.f = []; this.primes = []; } PrimeGenerator.prototype = { constructor: PrimeGenerator, generatePrimeNumbers(maxValue) { if (maxValue < 2) { return []; // 对不合理值返回空数组 } else { this.initializeSieve(maxValue); // this.sieve(); // this.loadPrimes(); return this.primes; } }, initializeSieve(maxValue) { this.s = maxValue + 1; this.f = []; let i; // 将数组初始化为true for (i = 0; i < this.s; i++) { this.f[i] = true; } // 去掉已知的非素数 this.f[0] = this.f[1] = false; } }; const primeGenerator = new PrimeGenerator(); const centArr = primeGenerator.generatePrimeNumbers(100); console.log(centArr);
这样修改后,this就会正确指向PrimeGenerator的实例,调用this.initializeSieve时就能找到原型上的方法了。
内容的提问来源于stack exchange,提问作者Donald33 Nevermore
相关产品推荐
相关产品推荐

