简体   繁体   中英

Cannot assign to read only property 'name' of object '[object Object]'

The following code will throw an error only for the name property. It could be fixed by specifying name property as writable in Object.create arguments but I'm trying to understand why is this happening (and maybe there is a more elegant way to fix it).

 var BaseClass = function (data) { Object.assign(this, data); } var ExtendedClass = function () { BaseClass.apply(this, arguments); } ExtendedClass.prototype = Object.create(BaseClass); console.log(new ExtendedClass({ type: 'foo' })); new ExtendedClass({ name: 'foo' });

If you get this error in Angular+Typescript+NgRX :

You can use the spread operator to take a shallow copy of a readonly object to make it readable, however you may not want this depending on your situation.

let x = [...y];

If you're using Redux / NgRX, there's a chance your selector could be returning a readonly object with a reference to the store, which can throw exceptions when trying to alter that object property via template binding. Depending on your situation, you can take a deep copy to remove the store reference.

let x = JSON.parse(JSON.stringify(y));

You cannot modify the name property of a function. The descriptor says it is not writable ...

 var BaseClass = function (data) { Object.assign(this, data); }; console.log(Object.getOwnPropertyDescriptor(BaseClass, 'name'));

But since it is configurable , you could use Object.defineProperty() .

 var BaseClass = function (data) { Object.assign(this, data); }; Object.defineProperty(BaseClass, 'name', { writable: true, value: 'Foo' }); console.log(BaseClass.name);


EDIT

I'm back! So... As I said previously in comments, I think I have identified your problem. I answered a bit too fast and did not see that your ES5 inheritance is wrong.

ExtendedClass.prototype = Object.create(BaseClass); is not what you want to do. Doing so means the prototype of ExtendedClass becomes a constructor function. This obviously generates an unexpected behavior.

 function BaseClass(data) { console.log(this instanceof BaseClass); // "this" is not an instance of "BaseClass" console.log(this instanceof Function); // "this" is a function console.log(this.name); // "this" is "BaseClass" Object.assign(this, data); } function ExtendedClass() { BaseClass.apply(this, arguments); } ExtendedClass.prototype = Object.create(BaseClass); new ExtendedClass({ type: 'foo' });

In your code, this is a function and refers to BaseClass . That is why you are not allowed to modify its name...

In fact, when working with inheritance in JavaScript, you generally need these two lines:

ExtendedClass.prototype = Object.create(BaseClass.prototype);
ExtendedClass.prototype.constructor = ExtendedClass;

Here is a valid implementation:

 function BaseClass(data) { console.log(this instanceof BaseClass); // "this" is an instance of "BaseClass" console.log(this instanceof Function); // "this" is not a function console.log(this.name); // "this" has no name yet Object.assign(this, data); } function ExtendedClass() { BaseClass.apply(this, arguments); } ExtendedClass.prototype = Object.create(BaseClass.prototype); ExtendedClass.prototype.constructor = ExtendedClass; var instance = new ExtendedClass({ name: 'foo' }); console.log(instance.name); // foo console.log(BaseClass.name); // BaseClass console.log(ExtendedClass.name); // ExtendedClass

The name is reserved property of Function object to which you are trying to set it in. You cannot set it.

documentation for name property is at MDN .

If you get this error in Angular+TypeScript :

WRONG / INVALID:

@Output whatever_var = new EventEmitter();

GOOD / CORRECT:

@Output() whatever_var = new EventEmitter();

使用 ES7+ 或 TypeScript 扩展运算符功能来解决这个问题

obj = { ...obj, name: { first: 'hey', last: 'there'} }

Most likely you're using readonly object that can't be edited. Use cloneDeep from lodash.

const x = cloneDeep(y);

where y is readonly object & use x instead of y in your code.

I ran into this issue in Angular, while setting a local variable from ActivatedRoute's queryParams, and attempting to conditionally either override or merge... Duplicating beforehand did the trick:

updateQp(qp = {}, force = false) { 
    let qpLoc = Object.assign({}, this.queryParamsLocal)
    this.queryParamsLocal = force ? qp : Object.assign(qpLoc, qp)
}

In my case, I was trying to swop 2 elements in an array in redux. Here's a simple way of how I altered the redux state while avoiding the readonly issue:

let newData = []
let data = store.getState().events.value

for(let i = 0; i < data.length; i++) {
  if(i === fromIndex) {
    newData.push(data[toIndex])
  }else if(i === toIndex) {
    newData.push(data[fromIndex])
  }else {
    newData.push(data[i])
  }
}
this.setEventsData(newData)

The above code creates a new empty array. It then iterates through the readonly array and pushes each item into the new array. This effectively creates a new array with the items of the readonly array positioned in a different order. If you are having trouble editing the values, you could alter the above code and create a new object with the altered values and insert that into the position where you'd like to make the change.

I bumped into this error once with Nestjs, and I fixed it by turning the property type to 'any'

type Product = {
  readonly owner: string;
};

const obj: Product = {
  owner: 'John',
};

(obj.owner as any) = 'James';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM