Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!