JavaScript私有方法

韦恩·高:

要使用公共方法创建JavaScript类,我需要执行以下操作:

function Restaurant() {}

Restaurant.prototype.buy_food = function(){
   // something here
}

Restaurant.prototype.use_restroom = function(){
   // something here
}

这样,我班的用户可以:

var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();

如何创建可以由buy_fooduse_restroom方法调用但不能由类用户在外部调用的私有方法

换句话说,我希望我的方法实现能够做到:

Restaurant.prototype.use_restroom = function() {
   this.private_stuff();
}

但这不起作用:

var r = new Restaurant();
r.private_stuff();

如何将其定义private_stuff为私有方法,使两者都适用?

我已经读过Doug Crockford的文章几次,但似乎公共方法不能调用“私有”方法,而外部可以调用“特权”方法。

26之17:

您可以做到,但缺点是它不能成为原型的一部分:

function Restaurant() {
    var myPrivateVar;

    var private_stuff = function() {  // Only visible inside Restaurant()
        myPrivateVar = "I can set this here!";
    }

    this.use_restroom = function() {  // use_restroom is visible to all
        private_stuff();
    }

    this.buy_food = function() {   // buy_food is visible to all
        private_stuff();
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章