JavaScript Classes

前端 未结 8 468
心在旅途
心在旅途 2020-12-07 09:21

I understand basic JavaScript pseudo-classes:

function Foo(bar) {
    this._bar = bar;
}

Foo.prototype.getBar = function() {
    return this._bar;
};

var f         


        
8条回答
  •  旧巷少年郎
    2020-12-07 10:08

    what about this :

    var Foo = (function() {
        // "private" variables 
        var _bar;
    
        // constructor
        function Foo() {};
    
        // add the methods to the prototype so that all of the 
        // Foo instances can access the private static
        Foo.prototype.getBar = function() {
            return _bar;
        };
        Foo.prototype.setBar = function(bar) {
            _bar = bar;
        };
    
        return Foo;
    })();
    

    And now we have instantiation, encapsulation and inheritance.
    But, there still is a problem. The private variable is static because it's shared across all instances of Foo. Quick demo :

    var a = new Foo();
    var b = new Foo();
    a.setBar('a');
    b.setBar('b');
    alert(a.getBar()); // alerts 'b' :(    
    

    A better approach might be using conventions for the private variables : any private variable should start with an underscore. This convention is well known and widely used, so when another programmer uses or alters your code and sees a variable starting with underscore, he'll know that it's private, for internal use only and he won't modify it.
    Here's the rewrite using this convention :

    var Foo = (function() {
        // constructor
        function Foo() {
            this._bar = "some value";
        };
    
        // add the methods to the prototype so that all of the 
        // Foo instances can access the private static
        Foo.prototype.getBar = function() {
            return this._bar;
        };
        Foo.prototype.setBar = function(bar) {
            this._bar = bar;
        };
    
        return Foo;
    })();
    

    Now we have instantiation, inheritance, but we've lost our encapsulation in favor of conventions :

    var a = new Foo();
    var b = new Foo();
    a.setBar('a');
    b.setBar('b');
    alert(a.getBar()); // alerts 'a' :) 
    alert(b.getBar()); // alerts 'b' :) 
    

    but the private vars are accessible :

    delete a._bar;
    b._bar = null;
    alert(a.getBar()); // alerts undefined :(
    alert(b.getBar()); // alerts null :(
    

提交回复
热议问题