JavaScript中的继承会导致未捕获的TypeError

Vin*_*nay 7 javascript oop inheritance

可能是我在这里遗漏了一些东西.请耐心等待我,因为我是javascript中的OOP新手.但我需要找到解决问题的方法.

我有这个代码.

var parent = function() {}
parent.prototype.someFunc = function() {
  return "a string";
}
Run Code Online (Sandbox Code Playgroud)

现在我尝试使用如下代码继承父级,

var child = function() {
    parent.call(this);
}
child.prototype = new parent();
Run Code Online (Sandbox Code Playgroud)

当我这样做时,它有效.

var obj = new child();
obj.someFunc();
Run Code Online (Sandbox Code Playgroud)

但是我希望在下面的子项中有someFunc(),

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

这样做会给我一个错误,Uncaught TypeError: Object [object global] has no method 'getLightBox'但据我所知,它this引用了当前的对象,我只是在这里混淆了如何解决这个问题.如果我错了,请纠正我.或者,如果有更好的方式,那么我想了解它.

Esa*_*ija 3

您忘记使用new. IE 你有代码child(...)而不是new child(...)

一些技巧:

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