相关疑难解决方法(0)

如何在javascript中从子类调用父方法?

我花了最后几个小时试图找到问题的解决方案,但似乎没有希望.

基本上我需要知道如何从子类调用父方法.到目前为止,我尝试过的所有内容都会导致无法正常工作或覆盖父方法.

我使用以下代码在javascript中设置OOP:

// SET UP OOP
// surrogate constructor (empty function)
function surrogateCtor() {}

function extend(base, sub) {
    // copy the prototype from the base to setup inheritance
    surrogateCtor.prototype = base.prototype;
    sub.prototype = new surrogateCtor();
    sub.prototype.constructor = sub;
}

// parent class
function ParentObject(name) {
    this.name = name;
}
// parent's methods
ParentObject.prototype = {
    myMethod: function(arg) {
        this.name = arg;
    }
}

// child
function ChildObject(name) {
    // call the parent's constructor
    ParentObject.call(this, name);
    this.myMethod = function(arg) { …
Run Code Online (Sandbox Code Playgroud)

javascript oop methods parent

134
推荐指数
4
解决办法
14万
查看次数

为什么在super()之前不允许这样做

我一直在React js编码.我已经读过在ES6课程中访问'this'我们需要先调用super(道具),我想知道为什么这是.答案我发现主要是谈论Javascript无法知道'这'是什么,除非超类叫做.我想知道这是什么意思,因为在构造函数之外,'this'被识别,我们每次都不调用super(props).

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}
Run Code Online (Sandbox Code Playgroud)

javascript es6-class

9
推荐指数
3
解决办法
4113
查看次数

标签 统计

javascript ×2

es6-class ×1

methods ×1

oop ×1

parent ×1