在从console.log隐藏时定义__proto__上的函数

时间:2016-07-07 23:15:59

标签: javascript

我可以在proto上定义函数吗?目标的一部分是在我console.log对象时使用getter和setter但不会产生任何噪音。我注意到原型上定义的任何内容都未包含在console.log

function ValueObject() {
    var authentication; //private variable

    __proto__.getAuthentication = function() {return authentication};
    __proto__.setAuthentication = function(val) {authentication = val};

    this.val = val;
}

期望的行为。

var vo1 = new ValueObject(1);
console.log(vo1); // ValueObject { val: 1 } (desired behavior)

我的目标是仅在console.log中显示值,同时隐藏库中用户的所有getter和setter,因为它们具有内部特性和用途。

当我实例化对象时,问题是getter和setter不可访问。

2 个答案:

答案 0 :(得分:1)

function ValueObject(val) {

    private_val = val; //private

    ValueObject.prototype.get =()=> {
        this.authentication = private_val;

        return this.authentication; // public now
    }
}
var auth = new ValueObject('test');
alert('private: '+auth.private_val); // can't receive, it's private hence undefined
alert('private: '+auth.authentication); // neither
alert('public: '+auth.get()); // here you can
恕我直言,那是基本的校长。应该有效 - ()=>function()的缩写。

编辑:,这里有一个set / get构造示例......这也应该有效:

function ValueObject() {

    var private_val; //private

    ValueObject.prototype.set =(val)=> {
        private_val = val; // private variable gets a value 
    }

    ValueObject.prototype.get =()=> {
        this.authentication = private_val; // public variable gets the private value 

        return this.authentication; // public now
    }
}
var auth = new ValueObject;
auth.set('test');
alert('private: '+auth.private_val); // can't receive, it's private hence undefined
alert('private: '+auth.authentication); // neither
alert('public: '+auth.get()); // here you can

check demo

答案 1 :(得分:0)

私有变量需要公开公开才能从原型链中访问它。如果您需要将变量设置为私有,则必须在控制台中查看公共函数。

相关问题