yarkov
@yarkov
Помог ответ? Отметь решением.

Как работают классы в ECMAScript 6?

Как получить доступ к свойствам класса-родителя из класса-наследника?
class Model {
    constructor(model) {
        this.model = model;
    }
}

class Api extends Model{
    constructor(model, url) {
        super(model);
        this._url = url;
    }
    
    set url(v){
        this._url = v;
    }
    
    get url(){
        return this._url;
    }

    getModel() {
        console.log("super.model: ", super.model); // ПОЧЕМУ super.model ЗДЕСЬ undefined??????
    }
}

var api = new Api({name: "Model name", data: []}, "http://api.example.com");
api.getModel();
  • Вопрос задан
  • 526 просмотров
Решения вопроса 1
bingo347
@bingo347 Куратор тега JavaScript
Crazy on performance...
// ПОЧЕМУ super.model ЗДЕСЬ undefined

Потому что Model.prototype не содержит свойства model

Пример:
es2015:
class A {
  constructor() {
     // ...
  }

  method() {
     // ...
  }

  static sMethod() {
    // ...
  }
}

class B extends A {
  constructor(x, y) {
    super(x);
    super.method(y);
  }
}

То же самое, на es5:
function A() {
  if(!(this instanceof A)) {
     throw new Error('Class constructor A cannot be invoked without \'new\'');
  }
  // ...
}
A.prototype.constructor = A;
A.prototype.method = function method() {
  // ...
};
A.sMethod = function sMethod() {
  // ...
};

function B(x, y) {
  if(!(this instanceof B)) {
     throw new Error('Class constructor B cannot be invoked without \'new\'');
  }
  A.call(this, x);
  A.prototype.method.call(this, y);
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
B.sMethod = A.sMethod; //static методы тоже наследуются
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
trevoga_su
@trevoga_su
тем не менее, тема super не раскрыта совершенно
Ответ написан
Комментировать
Комментировать
Ваш ответ на вопрос

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

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