@Sector567

Можно ли в классах наследоваться к уже созданному объекту?

Например вот наследование при помощи .prototype - как видно здесь есть две функции-конструктор, а наследование
может быть в любом месте. То есть сначала мы создаем конструкторы, а уже потом, если нужно, мы наследуемся в процессе работы.
function Animal1(){
		this.go = function(){
			return this.name + " бежит";
		}
	};

	function Cat1(name,width){
		this.name = name;
		this.width = width;
	}

	Cat1.prototype = new Animal1();
	let rizik = new Cat1("Рыжик_1",30);

	console.log(rizik.name);
	console.log(rizik.go());


С классами же все немного иначе, здесь мы сразу при создании класса должны указать будет ли он наследоваться или нет при помощи extends и super
class Animal{
		constructor(){
		}
		go(){
			return this.name + " бежит";
		}
	}

	class Cat extends Animal{
		constructor(name,width){
			super()
			this.name = name;
			this.width = width;
		}
	}

	let tom = new Cat("Том",30);

	console.log(tom.name);
	console.log(tom.go());


Так вот, возможно ли сделать так, чтобы наследоваться можно было не сразу при создании класса, а как с prototype - потом по ходу работы, если это будет нужно? Если нет, то не лучше ли использовать prorotype и функции конструкторы, а не классы?
  • Вопрос задан
  • 121 просмотр
Решения вопроса 2
Можно:

class Animal {}
class Cat {}

const animal = new Animal();
const cat = new Cat();

console.log(animal instanceof Animal); // true
console.log(animal instanceof Cat); // false
console.log(cat instanceof Animal); // false
console.log(cat instanceof Cat); // true

Reflect.setPrototypeOf(Cat.prototype, Animal.prototype);

console.log(animal instanceof Animal); // true
console.log(animal instanceof Cat); // false
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); // true
Ответ написан
Комментировать
@dimoff66
Кратко о себе: Я есть
У вас есть доступ к Cat.prototype и к Animal.prototype, в любой момент вы можете скопировать свойства, причем это отразится в том числе на уже созданных экземплярах класса

const extendMe = ({prototype: childProto}, {prototype: parentProto}) => {
  for (const key of Object.getOwnPropertyNames(parentProto)) {
    if (!(key in childProto)) {
      childProto[key] = parentProto[key]
    }   
  }
}

class Animal {
  name () { return 'Животное' } 
  legs () { return undefined }
  get isAnimal () {
    return true
  }
}

class Cat {
  name () { return 'Котик' } 
  legs () { return 15 }
}

const cat = new Cat()
console.log(cat.isAnimal) //undefined

extendMe(Cat, Animal)
console.log(cat.isAnimal) // true
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы