gpt4 book ai didi

javascript - javascript 超出最大调用堆栈大小

转载 作者:行者123 更新时间:2023-11-30 05:45:09 26 4
gpt4 key购买 nike

我在javascript中写了一个extend方法来实现继承:

function Class() {}

Class.prototype.create = function () {
var instance = new this();
instance.init();
return instance;
}


// extend method
Class.extend = Class.prototype.extend = function (props) {
var SubClass = function () {};

SubClass.prototype = Object.create(this.prototype);
for (var name in props) {
SubClass.prototype[name] = props[name];
}
SubClass.prototype.constructor = SubClass;

if (this.prototype.init) {
SubClass.prototype.callSuper = this.prototype.init;
}

SubClass.extend = SubClass.prototype.extend;
SubClass.create = SubClass.prototype.create;

return SubClass;
}


// level 1 inheritance
var Human = Class.extend({
init: function () {
}
});

// level 2 inheritance
var Man = Human.extend({
init: function () {
this.callSuper();
}
})

// level 3 inheritance
var American = Man.extend({
init: function () {
this.callSuper();
}
})

// initilization
American.create();

然后开发工具报Maximum call stack size exceeded

我认为 callSuper 方法导致了问题,callSuper 调用了 init,而 init 调用了 callSuper,两者具有相同的上下文。

但我不知道如何修复它!

谁能帮帮我?如何设置正确的上下文?

最佳答案

你有范围问题。这是解决方案:

function Class() {}

Class.prototype.create = function () {
var instance = new this();
instance.init();
return instance;
}


// extend method
Class.extend = Class.prototype.extend = function (props) {
var SubClass = function () {},
self = this;

SubClass.prototype = Object.create(this.prototype);
for (var name in props) {
SubClass.prototype[name] = props[name];
}
SubClass.prototype.constructor = SubClass;

if (this.prototype.init) {
SubClass.prototype.callSuper = function() {
self.prototype.init();
}
}

SubClass.extend = SubClass.prototype.extend;
SubClass.create = SubClass.prototype.create;

return SubClass;
}


// level 1 inheritance
var Human = Class.extend({
init: function () {
console.log("Human");
}
});

// level 2 inheritance
var Man = Human.extend({
init: function () {
console.log("Man");
this.callSuper();
}
})

// level 3 inheritance
var American = Man.extend({
init: function () {
console.log("American");
this.callSuper();
}
})

// initilization
American.create();

关键时刻是将 init 方法包装在一个闭包中:

SubClass.prototype.callSuper = function() {
self.prototype.init();
}

这是一个包含解决方案 http://jsfiddle.net/krasimir/vGHUg/6/ 的 jsfiddle

关于javascript - javascript 超出最大调用堆栈大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18354899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com