繁体   English   中英

如何在JavaScript中声明公共方法和私有方法

[英]How to declare public method and private method in JavaScript

我想知道我是否需要公共方法,我需要使用它

var TestClass = function() {

    this.pub = function() {
              blahblah;
        };

如果需要私有方法(内部方法),我需要使用

var TestClass = function() {

    var pri = function() {
              blahblah;
        };

这是真的?

不,这不是真的。 内部函数( pri )是一个函数,而不是一个方法。 虽然javascript中的差异可以忽略不计(因为每个函数都可以用作方法,反之亦然),你仍然无法将其称为this.pri() ,这可能是真正的私有方法。

作为旁注,尽管其Java语法相似,但Javascript,特别是其对象模型,与Java / C ++ / C#有很大不同。 特别是,Javascript中不存在封装等概念。

我通常使用这种模式,我没见过很多。 我这样做是为了避免以任何特殊方式订购我的方法。 如果all都是公共的,那么通常必须确保在方法调用之前声明调用的方法

var person = new Person("Mo", "Yo");
person.getFullname();
person.getFirstname();
person.getLastname();           

function Person(firstname, lastname) {
    var firstname, lastname;

    (function constructor(){
        setFirstname(firstname);
        setLastname(lastname)
    })();

    this.getFullname = getFullname;   // Makes getFullName() public 
    function getFullname() {
        // Will allow you to order method in whatever order you want. 
        // If we where to have it as just this.getFullname = function () {...} and same for firstname 
        // as it is normally done, then this.getFirstname would have to be placed before this method. 
        // A common pain in the ass, that you cannot order methods as you want!    
        return getFirstname() + ", " + getLastname();   
    }               

    this.getFirstname = getFirstname;
    function getFirstname() {
        return firstname;
    }

    function setFirstname(name){
        firstname = name;
    }

    this.getLastname = getLastname;
    function getLastname() {
        return lastname;
    }
    function setLastname(name) {
        lastname = name;
    }    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM