bind绑定构造函数报Cannot assign to read only property 'name'错误如何解决
错误原因
你调用userMsg.bind(User)时,是将userMsg执行时的this永久绑定为User构造函数本身(而非User的实例对象)。
JS中所有函数对象的内置name属性为只读属性,其值固定为函数定义时的名称,不可修改。当userMsg执行时,内部this.name = this.name || 'Unknown'代码尝试修改这个只读属性,因此抛出类型错误。
解决方案
根据你的预期需求,调整bind的绑定对象为可写入name属性的普通对象即可,常见实现方式有两种:
- 方案1:绑定User类的实例作为上下文
const User = function(name) { this.name = name } function userMsg(msg) { this.name = this.name || 'Unknown' return `${this.name} said: ${msg}` } // 传入User实例作为绑定的this对象 const newMsg = userMsg.bind(new User()) console.log(newMsg('say smth')) // 输出:Unknown said: say smth
- 方案2:直接绑定空对象作为上下文(不需要关联User逻辑时使用)
const User = function(name) { this.name = name } function userMsg(msg) { this.name = this.name || 'Unknown' return `${this.name} said: ${msg}` } // 传入空对象作为绑定的this对象 const newMsg = userMsg.bind({}) console.log(newMsg('say smth')) // 输出:Unknown said: say smth
内容的提问来源于stack exchange,提问作者Qugean
相关产品推荐
相关产品推荐

