gpt4 book ai didi

javascript - JavaScript 中的继承导致 Uncaught TypeError

转载 作者:数据小太阳 更新时间:2023-10-29 04:37:09 26 4
gpt4 key购买 nike

可能是我在这里遗漏了什么。请耐心等待,因为我是 JavaScript 中 OOP 的新手。但我需要找到解决我的问题的方法。

我有这个代码。

var parent = function() {}
parent.prototype.someFunc = function() {
return "a string";
}

现在我正在尝试使用如下代码继承父对象,

var child = function() {
parent.call(this);
}
child.prototype = new parent();

当我这样做时,它会起作用。

var obj = new child();
obj.someFunc();

但我想在 child 里面有 someFunc() ,如下所示,

var child = function() {
parent.call(this);
var someVal = this.someFunc(); // method from parent.
}
child.prototype = new parent();

这样做会给我一个错误,因为 Uncaught TypeError: Object [object global] has no method 'getLightBox' 但据我所知,this 指的是当前对象并且我只是对如何解决这个问题感到困惑。如果我错了,请纠正我。或者如果有更好的方法,那么我想知道。

最佳答案

您忘记使用 new。 IE。你有执行 child(...) 而不是 new child(...)

的代码

一些提示:

还有

  • 不要使用 new 链接原型(prototype),只需使用 Child.prototype = Object.create(Parent.prototype)

关于javascript - JavaScript 中的继承导致 Uncaught TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16997253/

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