实例方法未调用父方法

时间:2018-08-06 01:19:12

标签: javascript ecmascript-6

假设:

class Parent {
  foo = (message) => 'parent and ' + message
}

class Child extends Parent {
  foo = (message = 'child foo') => super.foo(message)
}

为什么跟随测试不能通过?

describe('Child', () => {
  it('should call parent foo and return \'parent and child foo\'', () => {
    const child = new Child()
    const expectedResponse = 'parent and child foo'

    const response = child.foo()

    expect(response).toBe(expectedResponse)
  })
})

引发错误:TypeError: (intermediate value).foo is not a function

Parent的foo是否应该存在并被调用?

2 个答案:

答案 0 :(得分:1)

将它们定义为方法时,效果很好。您遇到箭头功能上下文问题

class Parent {
  foo(message){return 'parent and ' + message} 
}

class Child extends Parent {
  foo(message = 'child foo'){return  super.foo(message)}
}
const child = new Child()
console.log(child.foo())

答案 1 :(得分:1)

看起来最好在类内部使用方法语法。 https://javascriptweblog.wordpress.com/2015/11/02/of-classes-and-arrow-functions-a-cautionary-tale/

“使用箭头函数作为类方法的替代者从未感到自在。方法应根据调用它们的实例来动态调整范围,但按定义,箭头函数是静态范围的。”