как вызвать родительский конструктор? - PullRequest
25 голосов
/ 08 июля 2011

Допустим, у меня есть следующий фрагмент кода.

function test(id) { alert(id); }

testChild.prototype = new test();

function testChild(){}

var instance = new testChild('hi');

Можно ли получить alert('hi')? Я получаю undefined сейчас.

Ответы [ 5 ]

100 голосов
/ 14 марта 2013

JS OOP ...

// parent class
var Test = function(id) {
    console.log(id);
};

// child class
var TestChild = function(id) {
    Test.call(this, id); // call parent constructor
};

// extend from parent class prototype
TestChild.prototype = Object.create(Test.prototype); // keeps the proto clean
TestChild.prototype.constructor = TestChild; // repair the inherited constructor

// end-use
var instance = new TestChild('foo');
16 голосов
/ 27 июля 2016

У вас уже есть много ответов, но я добавлю ES6, который, IMHO, является новым стандартным способом сделать это.

class Parent { 
  constructor() { alert('hi'); } 
}
class Child extends Parent { 
  // Optionally include a constructor definition here. Leaving it 
  // out means the parent constructor is automatically invoked.
  constructor() {
    // imagine doing some custom stuff for this derived class
    super();  // explicitly call parent constructor.
  }
}

// Instantiate one:
var foo = new Child();  // alert: hi
7 голосов
/ 08 июля 2011

Вот как вы делаете это в CoffeeScript:

class Test
  constructor: (id) -> alert(id)

class TestChild extends Test

instance = new TestChild('hi')

Нет, я не начинаю священную войну. Вместо этого я предлагаю взглянуть на полученный код JavaScript, чтобы увидеть, как можно реализовать подклассы:

// Function that does subclassing
var __extends = function(child, parent) {
  for (var key in parent) {
    if (Object.prototype.hasOwnProperty.call(parent, key)) {
      child[key] = parent[key];
    }
  }
  function ctor() { this.constructor = child; }
  ctor.prototype = parent.prototype;
  child.prototype = new ctor;
  child.__super__ = parent.prototype;
  return child;
};

// Our code
var Test, TestChild, instance;

Test = function(id) { alert(id); };

TestChild = function() {
  TestChild.__super__.constructor.apply(this, arguments);
}; __extends(TestChild, Test);

instance = new TestChild('hi');

// And we get an alert

См. Это в действии на http://jsfiddle.net/NGLMW/3/.

Чтобы остаться верным, код немного изменен и прокомментирован, чтобы быть более читабельным по сравнению с выводом CoffeeScript.

3 голосов
/ 24 февраля 2012

Используя преимущества переменных аргументов и метод apply () , вы можете сделать это следующим образом. Вот для этого примера скрипка .

function test(id) { alert(id); }
function testChild() {
  testChild.prototype.apply(this, arguments);
  alert('also doing my own stuff');
}
testChild.prototype = test;
var instance = new testChild('hi', 'unused', 'optional', 'args');
1 голос
/ 08 июля 2011

Вам нужно объявить function testChild(), прежде чем устанавливать его прототип.Затем вам нужно вызвать testChild.test для вызова метода.Я полагаю, что вы хотите установить testChild.prototype.test = test, тогда вы можете позвонить testChild.test('hi'), и он должен разрешиться правильно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...