JavaScript中调用person实例的say()提示“不是函数”问题求助
say is not a function的常见原因及修复方案 Hey there! Let's break down why you're getting that say is not a function error when calling your Person instance's method—this is super common, and usually boils down to a few easy-to-fix mistakes:
构造函数未正确挂载方法到实例/原型
A frequent slip-up is defining thesaymethod in a way that doesn't attach it to your Person instances. For example, this wrong approach keepssayprivate to the constructor scope:function Person(name) { this.name = name; // This creates a local variable, not an instance method var say = function() { console.log(`Hi, I'm ${this.name}`); } }Fix it by either attaching the method directly to
thisin the constructor, or (better for memory efficiency) adding it to the constructor's prototype:// Prototype approach (recommended) function Person(name) { this.name = name; } Person.prototype.say = function() { console.log(`Hi, I'm ${this.name}`); }; // Constructor instance method approach function Person(name) { this.name = name; this.say = function() { console.log(`Hi, I'm ${this.name}`); } }实例化时遗漏了
new关键字
If you call your constructor withoutnew,thiswon't point to a new Person instance—instead, it binds to the global object (in non-strict mode), and the function returnsundefinedby default. No instance means nosaymethod!// Wrong: no new keyword const person = Person("Alice"); // Correct: uses new to create an instance const person = new Person("Alice");To guard against this mistake, add a check inside your constructor:
function Person(name) { if (!(this instanceof Person)) { return new Person(name); } this.name = name; } Person.prototype.say = function() { console.log(`Hi, I'm ${this.name}`); };意外覆盖了原型对象
If you reassignPerson.prototypeto a brand new object after adding thesaymethod, you'll wipe out all previously attached prototype methods. Like this:Person.prototype.say = function() { /* ... */ }; // This replaces the entire prototype, losing the say method Person.prototype = { walk: function() { console.log("Walking..."); } };Fix this by using
Object.assignto merge new methods into the existing prototype instead of replacing it:Object.assign(Person.prototype, { walk: function() { console.log("Walking..."); } });ES6类定义中的语法错误
If you're using ES6 classes, a tiny syntax mistake can prevent the method from being recognized. For example, mixing up arrow function syntax or forgetting parentheses:// Wrong: invalid method syntax class Person { constructor(name) { this.name = name; } say => { // This is not how class methods are defined console.log(`Hi, I'm ${this.name}`); } } // Correct: standard class method syntax class Person { constructor(name) { this.name = name; } say() { console.log(`Hi, I'm ${this.name}`); } }
内容的提问来源于stack exchange,提问作者J C

