Скажем, у меня есть следующий фрагмент кода.
function test(id) { alert(id); }
testChild.prototype = new test();
function testChild(){}
var instance = new testChild('hi');
Можно ли получить alert('hi')
? Теперь я получаю undefined
.
Скажем, у меня есть следующий фрагмент кода.
function test(id) { alert(id); }
testChild.prototype = new test();
function testChild(){}
var instance = new testChild('hi');
Можно ли получить alert('hi')
? Теперь я получаю undefined
.
Как вы это делаете в 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.
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');
У вас уже есть много ответов, но я заберу путь 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
Воспользовавшись переменными аргументами и apply(), вы можете сделать это таким образом. Здесь fiddle для этого примера.
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');
Вам нужно объявить function testChild()
, прежде чем устанавливать его прототип. Затем вам нужно вызвать testChild.test
, чтобы вызвать метод. Я считаю, что вы хотите установить testChild.prototype.test = test
, тогда вы можете вызвать testChild.test('hi')
, и он должен правильно разрешаться.