JavaScript 私有方法 [英] JavaScript private methods

查看:38
本文介绍了JavaScript 私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

To make a JavaScript class with a public method I'd do something like:

function Restaurant() {}

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

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

这样我的班级用户可以:

That way users of my class can:

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

如何创建一个可以被 buy_fooduse_restroom 方法调用但不能被类的用户从外部调用的私有方法?

How do I create a private method that can be called by the buy_food and use_restroom methods but not externally by users of the class?

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

In other words, I want my method implementation to be able to do:

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

但这应该行不通:

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

如何将 private_stuff 定义为私有方法,使这两个方法都成立?

How do I define private_stuff as a private method so both of these hold true?

我已经阅读了几次 Doug Crockford 的文章,但它似乎不是私有方法可以被公共方法调用,而特权"方法可以被外部调用.

I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.

推荐答案

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

You can do it, but the downside is that it can't be part of the prototype:

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();
    }
}

这篇关于JavaScript 私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆