使用此指针调用公共方法内的方法

时间:2013-02-24 09:36:13

标签: javascript module

我在JavaScript中使用私有/公共方法的下一个语法:

function Cars() {
    this.carModel = "";
    this.getCarModel = function () { return this.carModel; }
    this.alertModel = function () {alert (this.getCarModel());}
}

但是,当我调用方法alertModel时,由于this指向window对象,因此无法找到它: alert (this.getCarModel()); - this指向窗口

var newObject = new Cars();
newObject.alertModel();

我也尝试在prototype中声明这些方法,但它的行为相同。

Cars.prototype.getCarModel = function () {
    this.getCarModel = function () { return this.carModel; }
}
Cars.prototype.alertModel = function () {
alert (this.getCarModel());
}

我正在做的是在没有like的情况下调用它:

  Cars.prototype.alertModel = function () {
    alert (newObject.getCarModel());
    }

这是唯一的方法吗?因为在其他方法中它的作品。

3 个答案:

答案 0 :(得分:0)

您的问题是您基本上已在范围内声明了自由浮动函数。 您需要了解Javascript中Scope和Context之间的区别。有趣的是,Pragmatic Coffeescript对此进行了很好的讨论。 This is another good resource

答案 1 :(得分:0)

试试这个:

function Cars() {
    var carModel = "";
    this.getCarModel = function() { return carModel; };
    this.alertCarModel = function() { alert (carModel) };
}

这样carModel将是私有的,无法通过alertCarModel和getCarModel方法公开访问。

答案 2 :(得分:0)

试试这个:

function Cars() {
    this.carModel = "";
    this.getCarModel = function () { return this.carModel; }
    this.alertModel = function () {alert (this.getCarModel());}

    return {
     getCarModel: getCarModel,
     alertModel: alertModel
    }
}

var newObject = new Cars();
newObject.alertModel();
相关问题