JavaScript对象代码报错this.signIn不是函数,求问题排查
问题排查:
this.signIn is not a function 报错原因及修复方案 你碰到的这个报错,核心问题出在事件回调里的this指向不符合预期,咱们一步步拆解来看:
为什么会报错?
在socialAppFunctions的loginButton方法中,你给按钮绑定了一个匿名点击回调:
loginButton.addEventListener("click", function() { // ... this.signIn(userName.value, passWord.value); });
当按钮被点击触发这个回调时,函数内部的this默认指向的是触发事件的DOM元素(也就是#loginButton按钮),而不是你期望的socialAppFunctions对象。按钮元素上并没有signIn方法,所以自然会抛出this.signIn is not a function的错误。
而你把方法拆成独立函数时,这些函数属于全局作用域,直接调用signIn()相当于调用window.signIn(),不存在this指向混淆的问题,所以能正常运行。
修复方案(三种常用方法)
1. 提前保存this的引用
在loginButton方法里,先把当前对象的this存到一个变量(比如that)中,回调里用这个变量访问对象方法:
loginButton: function () { let loginButton = document.querySelector("#loginButton"); const that = this; // 保存当前对象的this引用 loginButton.addEventListener("click", function() { let userName = document.querySelector("#user"); let passWord = document.querySelector("#pass"); that.signIn(userName.value, passWord.value); // 使用that代替this }); },
2. 使用箭头函数
箭头函数不会绑定自己的this,它会继承外层作用域的this。把回调改成箭头函数后,内部的this就会指向loginButton方法执行时的this(也就是socialAppFunctions对象):
loginButton: function () { let loginButton = document.querySelector("#loginButton"); loginButton.addEventListener("click", () => { let userName = document.querySelector("#user"); let passWord = document.querySelector("#pass"); this.signIn(userName.value, passWord.value); // 此时this指向socialAppFunctions }); },
3. 用bind()显式绑定this
通过bind()方法给回调函数强制绑定this指向,让它始终指向socialAppFunctions:
loginButton: function () { let loginButton = document.querySelector("#loginButton"); loginButton.addEventListener("click", function() { let userName = document.querySelector("#user"); let passWord = document.querySelector("#pass"); this.signIn(userName.value, passWord.value); }.bind(this)); // 绑定当前this到回调函数 },
这三种方法都能解决this指向的问题,选你习惯的方式就行,本质都是确保回调里的this指向你的socialAppFunctions对象。
内容的提问来源于stack exchange,提问作者Ace
相关产品推荐
相关产品推荐

