无法绑定到新的构造函数
cannot bind to new constructor function
以下代码将抛出名称 属性 的类型错误:
无法分配给函数的只读 属性 'name'。
我希望获得用户名 'Unknown'
如果我像这样使用绑定,我会得到这个结果:
const User = function(name) {
this.name = name
}
function userMsg(msg) {
this.name = this.name || 'Unknown'
return `${this.name} said: ${msg}`
}
const newMsg = userMsg.bind(User)
newMsg('say smth')
您当前的代码试图在 userMsg
中使用 User
构造函数作为 this
。这会导致您在 function
的上下文中执行 userMsg
的问题。函数有一个你不能覆盖的只读 属性 name
,它来自 Function.prototype.name
.
幸运的是,这不是你想要做的。如果您不是绑定 User
函数而是绑定通过调用构造函数创建的 实例 ,您可以坚持使用 属性 name
:
const User = function(name) {
this.name = name
}
function userMsg(msg) {
this.name = this.name || 'Unknown'
return `${this.name} said: ${msg}`
}
const max = new User('Max'); // you need a User instance to bind to
const newMsg = userMsg.bind(max); // bind it here
console.log(newMsg('say smth'));
在实际使用中,你可能也不想使用bind
,而是在User.prototype
中加上userMsg
:
const User = function(name) {
this.name = name
}
User.prototype.userMsg = function(msg) {
return `${this.name} says: ${msg}`
}
const max = new User('Max');
const newMsg = max.userMsg('Hello!'); // now we can call the function on the user
console.log(newMsg);
或者至少,不要永久地bind
它,而是使用call
来使用一次用户上下文:
const User = function(name) {
this.name = name
}
function userMsg(msg) {
this.name = this.name || 'Unknown'
return `${this.name} said: ${msg}`
}
const max = new User('Max');
const newMsg = userMsg.call(max, 'say smth'); // use call to set context only for this call
console.log(newMsg);
以下代码将抛出名称 属性 的类型错误:
无法分配给函数的只读 属性 'name'。
我希望获得用户名 'Unknown'
如果我像这样使用绑定,我会得到这个结果:
const User = function(name) {
this.name = name
}
function userMsg(msg) {
this.name = this.name || 'Unknown'
return `${this.name} said: ${msg}`
}
const newMsg = userMsg.bind(User)
newMsg('say smth')
您当前的代码试图在 userMsg
中使用 User
构造函数作为 this
。这会导致您在 function
的上下文中执行 userMsg
的问题。函数有一个你不能覆盖的只读 属性 name
,它来自 Function.prototype.name
.
幸运的是,这不是你想要做的。如果您不是绑定 User
函数而是绑定通过调用构造函数创建的 实例 ,您可以坚持使用 属性 name
:
const User = function(name) {
this.name = name
}
function userMsg(msg) {
this.name = this.name || 'Unknown'
return `${this.name} said: ${msg}`
}
const max = new User('Max'); // you need a User instance to bind to
const newMsg = userMsg.bind(max); // bind it here
console.log(newMsg('say smth'));
在实际使用中,你可能也不想使用bind
,而是在User.prototype
中加上userMsg
:
const User = function(name) {
this.name = name
}
User.prototype.userMsg = function(msg) {
return `${this.name} says: ${msg}`
}
const max = new User('Max');
const newMsg = max.userMsg('Hello!'); // now we can call the function on the user
console.log(newMsg);
或者至少,不要永久地bind
它,而是使用call
来使用一次用户上下文:
const User = function(name) {
this.name = name
}
function userMsg(msg) {
this.name = this.name || 'Unknown'
return `${this.name} said: ${msg}`
}
const max = new User('Max');
const newMsg = userMsg.call(max, 'say smth'); // use call to set context only for this call
console.log(newMsg);