Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
cannot bind to new constructor function

the following code will throw an type error for the name property: Cannot assign to read only property 'name' of function.
I expect to get user name 'Unknown' I get this result if i use bind like:

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')

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your current code is trying to use the User constructor function as this inside userMsg. That causes the problem that you are executing userMsg in the context of a function. Functions have a read-only property name which you cannot overwrite, which comes from Function.prototype.name.

Luckily, that is not what you want to do anyway. If you instead of binding the User function bind an instance created by calling the contructor function, you can stick to your property 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'));

In actual use, you probably also don't want to use bind, but rather add userMsg to the User.prototype:

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);

or at least, don't bind it permanently, but rather use call to use the user context once:

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);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda