Javascript对象箭头功能及此

问题描述 投票:0回答:1

[学习JS和this关键字的行为...想了解下面发生的事情

声明一个类(point2)

class point2 {
    constructor(x,y) {
        this.x = x;
        this.y=y;
    }
    dump() {
        (print = () => {
            console.log(this.x + " " + this.y);
        }).call(this);
    }
}

p1 = new point2(1,2);
p1.dump(); // prints undefined 

但不知道为什么p1.dump()调用未打印

[以为p1.dump()会将其设置为point2对象,然后print arrow函数将继承this(这将是point2对象),因此希望它可以打印1 2

javascript this arrow-functions
1个回答
0
投票

[p1.dump()返回undefined,因为您什么都不返回。

class point2 {
    constructor(x,y) {
        this.x = x;
        this.y=y;
    }
    dump() {
        (print = () => {
            console.log(this.x + " " + this.y);
        }).call(this);

        return true; // return something here and the console.log will have result
    }
}

p1 = new point2(1,2);
p1.dump(); // undefined

Try it on devtool

undefined是方法返回的内容。因此,由于该方法没有return关键字,因此它将返回undefined1 2已按预期方式注销。

© www.soinside.com 2019 - 2024. All rights reserved.