封装/数据隐藏在Javascript中?

时间:2016-02-05 15:10:52

标签: javascript oop object encapsulation data-hiding

我想了解JavaScript中Encapsulation的概念,以及如何将我的属性和方法设为公共或私有。

我正在玩这个例子:

    var person = function(newName, newAge) {

    // Private variables / properties
    var name = newName;
    var age = newAge;

    // Public methods
    this.getName = function() {
        return name;
    }

    // Private methods
    var getAge = function() {
        return age;
    }

    // Public method, has acces to private methods
    this.giveAge = function() {
        return getAge();
    }
}

var jack = new person("Jack", 30);

console.log(jack.name); // undefined
console.log(jack.getName); // Jack
console.log(jack.getAge()); // TypeError: jack.getAge is not a function
console.log(jack.getAge); // undefined
console.log(jack.giveAge()); // 30

因此,变量var namevar age是私有的。要访问它们,我使用.this引用来使用公共方法。因此,我的函数中var内的任何内容都是私有的,并且我的对象中的.this内的任何内容都可以在外部看到。

我猜这个人的原因是可见的,所以它暴露了它的所有属性。

我是否在正确的轨道上?这是隐藏或公开您的属性/方法的正确方法吗?

还有一个问题,为什么console.log(jack.getAge());会抛出错误?当引用函数I"存储"在变量中,如果我把()放在该函数的末尾,它可以两种方式工作,所以我不知道有什么用?

谢谢!

2 个答案:

答案 0 :(得分:3)

  

我猜这是因为人是可见的,所以它暴露了它的所有属性。

正确。

  

我是否在正确的轨道上?这是隐藏或公开您的属性/方法的正确方法吗?

如果你想这样做,那么是的,这是一种相当标准的方法。至少在ES2015中还有另一种方法,但(可能)有更多的开销。

  

还有一个问题,为什么console.log(jack.getAge());抛出错误?

由于jack对象没有getAge属性,因此jack.getAge会产生undefined,这不是一个函数。在getAge闭包有权访问的上下文中有一个giveAge 变量(以及agename),但是{{1} }没有jack属性。

  

当引用函数我“存储”在变量中时,如果我把()放在该函数的末尾,它可以两种方式工作,所以我不知道有什么用?

不,它不是双向的。 getAge获取对该函数的引用。 jack.getName 调用函数并获取其返回值。

我应该注意jack.getName()函数没有意义。它只能在getAge函数中定义的闭包中访问,就像personage一样。因此,任何使用name的内容都只会使用getAge来避免函数调用。

为了完整起见,我会注意到很多人并不担心JavaScript中真正的私有属性,而是选择“按惯例私有” - 例如,他们使用命名约定(这些名称以{{1}开头})意思是“不要触摸它们,它们是私密的”。这对阻止人们使用它们没有任何作用,当然,它只是表明他们不应该这样做。提倡这一点的人通常会指出,在许多具有“真实”私有属性/字段(Java,C#)的语言中,只需要通过反射进行少量努力即可访问这些属性/字段。因此,论证说,只是使用命名约定是“私有的”。

我不同意(也没有特别不同意),在Java或C#中需要更多的工作来访问私有属性而不是公共属性。我只是注意到“按惯例私有”的做法非常普遍,并且经常“足够好”。

答案 1 :(得分:1)

  
    

我猜这个人的原因是可见的,所以它暴露了它的所有属性。

  

不完全正确。首先,人是一种常规功能。它可以在没有new-keyword的情况下完全调用,但结果会炸毁整个应用程序。

要了解原因,您应该首先了解new-keyword在幕后的作用。这将是一个js实现:

function fakeNew(constructor, ...args){
    if(typeof constructor !== "function"){
        throw new TypeError(constructor + " is not a constructor");
    }

    //create a new Instance of the constructors prototype-property
    var instance = Object.create(constructor.prototype);

    //invoke the constructor with the scope set to the instance and the provided arguments
    var result = constructor.apply(instance, args);

    //check wether the returned value is an Object (and functions are considered as Objects)
    if(result === Object(result)){
        //then return the result-value in favor to the instance
        return result;
    }

    //otherwise return the instance
    return instance;
}

另一方面,任何函数也可以是构造函数;没有特殊需要,这完全取决于你。

回到杰克

var jack = person("Jack", 30);  //would result in the following desaster:
console.log(jack);      //undefined, since person doesn't return anthing

console.log(jack.getName());    
//will throw, since jack is still undefined, and therefore doesn't have any properties

//BUT:
console.log(window.getName())   //will return "Jack" now

console.log(window.getAge);     //undefined, but this is fine 
//global scope has not been polluted with this one, cause getAge was a local variable inside the function-call

console.log(window.giveAge())   //can still call the enclosed (private) function getAge()

然后

var jill = person("Jill", 28);
//will overwrite the global functions and expose new values now
console.log(window.getName(), window.giveAge()) //"Jill", 28    
//and Jack is kind of gone, well the variable is left but the variable contained undefined, so...

接下来的事情就是确定范围。让我们假设你做的正确

//first let's add a function that executes on the scope
//inside the constructor
this.getNameAndAge = function(){
    return this.getName() + ": " + getAge();
}

var andy = new person("Andy", 45);
var joe = new person("Joe", 32);

//let's make Andy a little younger
andy.getNameAndAge = joe.getNameAndAge;
console.log(andy.getNameAndAge(), andy.getName() + ": " + andy.giveAge());
//will result in "Andy: 32", "Andy": 45

waaaaat?

你已经覆盖了公共方法getNameAndAge 通过在当前对象上调用(也是公共的)方法getName()来访问该名称。
但是giveAge()仍然是来自getNameAndAge-function"的特定"实例的范围内的封闭变量。被宣布,因此它来自Joe的函数调用。

要了解这一点的影响,让我们的范围更加奇怪

funciton Animal(species, _name){
    //species is likewise a local variable and can be enclosed, modified, or whatever
    //we don't need to write it to some different variable

    //but we want to expose the name of this animal, since it should be possible to change it later
    //without the need to create a getter and a setter just to change the property of _name
    this.name = _name;

    this.whoAreYou = function(){
        //so we concat the enclosed value from species with the name-argument on this object
        //in the hope that everything will be alright.
        return species + " " + this.name;
    }
}

var jack = new Animal("dog", "Jack");
var jill = new Animal("cat", "Jill");
var joe = new Animal("fish", "Joe");

console.log(jack.whoAreYou());  //"dog Jack"
console.log(jill.whoAreYou());  //"cat Jill"
console.log(joe.whoAreYou());   //"fish Joe"

//as far so good; till now ...
//since these properties are still writable someone will start and move them around

//maybe like a callback
function someFunction(someArg, callback){
    console.log(someArg, callback());
}
someFunction("Who are you?", jack.whoAreYou);

//or sth. like this:
//you may not believe that someone would ever do that, but it will happen!
jack.whoAreYou = jill.whoAreYou;
console.log(jack.whoAreYou());

//and now the poor dog has an Identity-crisis.
//the first one will result in:
"Who are you?", "dog undefined"

//the latter will log "cat Jack"

or even more fummy if sth. like this happens:

var fn = joe.whoAreYou;
console.log(fn.call(jack), fn.call(jill), fn.call(joe), fn.call(Animal));
//cause now they are all fishes, even the Animal-constuctor

我不想说这很糟糕,或者你应该避免它但是它的方式是有效的,应该考虑这一点。

因为这种方式为我们提供了原型继承,并且是编写mixins的好方法,而无需一直编写包装方法。

您可以将其视为"我需要保护我的私人状态"或者"我在您提供给我的任何环境中工作"

  
    

还有一个问题,为什么console.log(jack.getAge());抛出错误?

  

因为jack.getAge未定义且未定义不是函数

var getAge = function() {
    return age;
}

对此行的另一个评论

JS函数和变量声明中的

被提升,因此可以从函数的开头获得。表达式不是。

var person = function(){
    //...
    foo();
    bar();
    baz();

    function foo(){ console.log("this will work"); }
    var bar = function(){ console.log("this will fail"); }
    //because to this point, bar was delared and assigned with undefined, 
    //and we remember? undefined can't be invoked

    return whatever;

    function baz(){ console.log("event this would work"); }
    //unless some preprocessor decided (falsely), that this function can be removed 
    //since it is after the return-statement, and is therefore unreachable
}