It is not possible to assign only the property name 'object name' [object object] '

The following code throws an error only for the property name. This can be fixed by specifying the property nameas being written to the arguments Object.create, but I'm trying to understand why this is happening (and there may be 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' });
Run codeHide result
+9
source share
4 answers

You cannot change a property of a namefunction. The descriptor says this is not writable...

var BaseClass = function (data) {
  Object.assign(this, data);
};

console.log(Object.getOwnPropertyDescriptor(BaseClass, 'name'));
Run codeHide result

But since this configurable, you can use Object.defineProperty().

var BaseClass = function (data) {
  Object.assign(this, data);
};

Object.defineProperty(BaseClass, 'name', {
  writable: true,
  value: 'Foo'
});

console.log(BaseClass.name);
Run codeHide result

EDIT

! ... , , . , ES5 .

ExtendedClass.prototype = Object.create(BaseClass); - , . , ExtendedClass . , , .

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' });
Hide result

this BaseClass. ...

, JavaScript :

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

:

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
Hide result
+6

name Function, . .

name MDN.

+3

Angular + TypeScript:

WRONG/INVALID:

@Output any_var = new EventEmitter();

GOOD/CORRECT:

@Output() any_var = new EventEmitter();

+1

Angular + Typescript + NgRX:

, , , .

let x = [...y];

Redux/NgRX, , , . , .

let x = JSON.parse(JSON.stringify(y));
+1
source

Source: https://habr.com/ru/post/1678276/


All Articles