无法在调用时读取未定义的属性 X

所以我有一堂课


class A {

    test() {

        return 1;

    }

    foo() {

        return this.baz(this.bar)

    }

    bar() {

        return this.baz(this.test);

    }

    baz(f){

        return f(); 

    }

}

当我调用方法时 foo


var a = new A();

a.foo();

我得到


Uncaught TypeError: Cannot read property 'baz' of undefined

    at bar (<anonymous>:9:15)

    at A.baz (<anonymous>:12:10)

    at A.foo (<anonymous>:6:15)

    at <anonymous>:1:3

this在调用方法 f() 后,它是如何变得未定义的,我该如何解决这个问题?


慕妹3146593
浏览 135回答 3
3回答

小唯快跑啊

通过这样做:return this.baz(this.bar)你只是传递一个函数没有指定什么this它this是指(无上下文)。所以最终,当你进入baz(f)方法时,你得到一个函数作为参数,而不是类的方法A。所以它this是未定义的。要修复它,您有两个选择,第一个是更改foo()方法:foo() {&nbsp; &nbsp; return this.baz(this.bar.bind(this))}第二个是改变baz(f)方法:baz(f){&nbsp; &nbsp; return f.call(this);&nbsp;}这两种解决方案都适用于这种情况。希望能帮助到你

饮歌长啸

它从未被定义。您在没有上下文的情况下调用函数 - 所以没有“this”this.apply(f) 将它绑定到对象

慕桂英3389331

你也可以使用箭头函数来解决这个问题。class A {&nbsp; &nbsp; test =()=> {&nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; }&nbsp; &nbsp; foo=()=> {&nbsp; &nbsp; &nbsp; &nbsp; return this.baz(this.bar)&nbsp; &nbsp; }&nbsp; &nbsp; bar=()=> {&nbsp; &nbsp; &nbsp; &nbsp; return this.baz(this.test);&nbsp; &nbsp; }&nbsp; &nbsp; baz=(f)=>{&nbsp; &nbsp; &nbsp; &nbsp; return f();&nbsp;&nbsp; &nbsp; }}const a = new A()console.log(a.foo())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript