简体   繁体   English

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

[英]defining functions on __proto__ while hiding from console.log

Can I define functions on proto? 我可以在原型上定义函数吗? Part of the objective is to have getter and setters but not creating any noise when I console.log the object. 目标的一部分是要有吸气剂和塞子剂,但在我console.log对象时不会产生任何噪音。 I've noticed anything defined on prototype is not included in the console.log . 我注意到在console.log没有包含任何在原型上定义的内容。

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

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

    this.val = val;
}

Desired behavior. 所需的行为。

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

My objective is to show value only in console.log while hiding all those getters and setters from user of the library because they are of internal nature and use. 我的目标是仅在console.log显示价值,同时对库用户隐藏所有这些getter和setter,因为它们是内部性质和用途。

The problem is getter and setters are not accessible when i instantiate the object. 问题是getter,当我实例化对象时,setter无法访问。

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

IMHO, that's the basic principal. 恕我直言,这是基本原理。 should be working - and ()=> is short for function() . 应该正常工作- ()=>function()缩写。

EDIT: and here for a set/get construct example... this should work too: 编辑:和这里的设置/获取构造示例...这也应该工作:

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 检查演示

The private variable needs to be publicly exposed in order to access it from the prototype chain. 为了从原型链访问它,需要公开暴露私有变量。 If you need the variable to be private, you will have to deal with seeing the public functions in the console. 如果您需要将该变量设为私有,则必须在控制台中查看公共函数。

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

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