javascript中两种类方法的定义

第一种方法:

function Point(x, y) {
    this.x = x;
    this.y = y;

    this.delta = function (delta) {
        this.x += delta.x;
        this.y += delta.y;
    }
}

生成的每个对象都有一份delta()函数:
对象图
第二种方法:
采用prototype:

function Point(x, y) {
    this.x = x;
    this.y = y;
}

Point.prototype.delta = function (delta) {
    this.x += delta.x;
    this.y += delta.y;
}

这样就避免了每个Point对象都有一个delta()方法:
对象图

猜你喜欢

转载自blog.csdn.net/bluejoe2000/article/details/79080296
今日推荐