Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Бесконечной рекурсия (https://javascript.ru/forum/misc/44031-beskonechnojj-rekursiya.html)

rekzi 03.01.2014 12:27

Бесконечной рекурсия
 
function foo() {}
foo.prototype.identify = function() {
	return "I'm a foo";
}

function bar() {}
extend(bar, foo)
bar.prototype.identify = function() {
	return "I'm a bar and " +
	this.constructor.superclass.identify.apply(this, arguments);
}

function zot() {}
extend(zot, bar)
zot.prototype.identify = function() {
	return "I'm a zot and " +
	this.constructor.superclass.identify.apply(this, arguments);
}

f = new foo();

alert(f.identify()); // "I'm a foo"

b = new bar();

alert(b.identify()); // "I'm a bar and I'm a foo"

z = new zot();

alert(z.identify()); // stack overflow
Не могу понять пример, почему обращение происходит к дочернему классу zot из bar? Из-за передаваемого контекста this в apply?

BallsShaped 03.01.2014 12:44

В общих чертах: так в js не делают. Для экземпляра zot, this.constructor.superclass === bar.prototype. И, соотвественно, this.constructor.superclass.identify в bar.prototype.identify ссылается сам на себя. Делают так:
function foo() {}
foo.prototype.identify = function() {
    return "I'm a foo";
}
 
function bar() {}
extend(bar, foo)
bar.prototype.identify = function() {
    return "I'm a bar and " +
    foo.prototype.identify.apply(this, arguments);
}
 
function zot() {}
extend(zot, bar)
zot.prototype.identify = function() {
    return "I'm a zot and " +
    bar.prototype.identify.apply(this, arguments);
}

rekzi 03.01.2014 13:26

Разобрался. This в bar будет являться экземпляром zot.


Часовой пояс GMT +3, время: 07:41.