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

Answer

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