Simulate getter in JavaScript by valueOf and toString method

function Foo(a, b) {
    this.a = a;
    this.b = b;

    // simulate getter via valueOf and toString method
    this.sum = {
        valueOf: function () {
            return a + b
        },
        toString: function () {
            return a + b
        }
    }
}
alert(new Foo(2, 3).sum);

posted @ 2014-08-17 21:59  PengpengSong  阅读(186)  评论(0编辑  收藏  举报