【问题标题】:es6 super propMethod call super other propMethodes6 super propMethod 调用 super 其他 propMethod
【发布时间】:2018-02-14 10:48:07
【问题描述】:

我用的是nodejs 6.10.3,代码如下,es6类继承有问题。

'use strict';

class Foo {
    constructor() {}
    hi() {
        console.log('foo.hi');
        this._hi();
    }
    _hi() {
        console.log('foo._hi');
    }
}

class Goo extends Foo {
    constructor() {
        super();
    }
    hi() {
        console.log('goo.hi');
        super.hi();
    }
    _hi() {
        console.log('goo._hi');
    }
}

let goo = new Goo();
goo.hi();

console.log 输出是这样的。

// goo.hi
// foo.hi
// goo._hi

但我需要这个。

// goo.hi
// foo.hi
// foo._hi

我该怎么办?

【问题讨论】:

  • 干脆不要重写方法?

标签: javascript node.js ecmascript-6


【解决方案1】:

super 将初始化 this

'use strict';

class Foo {
    constructor() {}
    hi() {
        console.log('foo.hi');
        this._hi();
    }
    _hi() {
        console.log('foo._hi');
    }
}

class Goo extends Foo {
    constructor() {
        super();
    }
    hi() {
        console.log('goo.hi');
        Foo.prototype.hi();
    }
    _hi() {
        console.log('goo._hi');
    }
}

let goo = new Goo();
goo.hi();

【讨论】:

  • 现在this 将引用Foo.prototype。该方法将无权访问实例数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 2012-06-12
  • 1970-01-01
  • 2012-08-08
  • 2017-05-23
相关资源
最近更新 更多