我刚学nodejs,有个题目,有没有会的大佬解答一下。

class Cash {
//你需要书写的代码

    }
    const cash1 = new Cash(105);
    const cash2 = new Cash(66);
    const cash3 = cash1.add(cash2);
    const cash4 = Cash.add(cash1, cash2);
    Console.log(`${cash3}`, `${cash4}`);

    //代码输出结果为:1元7角1分 1元7角1分

2个回答

图片说明

class Cash {
    constructor(x) {
        this.x = x;
    }
    add(a) {
        return parseInt((a.x + this.x) / 100) + '元' + parseInt((a.x + this.x) % 100 / 10) + '角' + (a.x + this.x) % 10 + '分'
    }
    static add(a, b) {
        return parseInt((a.x + b.x) / 100) + '元' + parseInt((a.x + b.x) % 100 / 10) + '角' + (a.x + b.x) % 10 + '分'
    }
}

const cash1 = new Cash(105);
const cash2 = new Cash(66);
const cash3 = cash1.add(cash2);
const cash4 = Cash.add(cash1, cash2);
console.log(`${cash3}`, `${cash4}`);
class Cash {
    constructor(value) {
        this.value = value;
    }
    add(a) {
        return new Cash(a.value + this.value);
    }
    static add(a, b) {
        return new Cash(a.value + b.value);
    }
    toString() {
        const tmp = this.value % 100;
        const y = (this.value - tmp) / 100 >>> 0;
        const f = tmp % 10;
        const j = (tmp - f) / 10 >>> 0;
        return `${y}元${j}角${f}分`;
    }
}

const cash1 = new Cash(105);
const cash2 = new Cash(66);
const cash3 = cash1.add(cash2);
const cash4 = Cash.add(cash1, cash2);
console.log(`${cash3}`, `${cash4}`);

// 虽然我对非静态add方法不改变this而是像静态方法一样返回新对象感觉很怪异
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问