Skip to content

Instantly share code, notes, and snippets.

@zerobias
Last active October 20, 2016 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerobias/85efeea9e6dc5ba1eda4a63af17574dc to your computer and use it in GitHub Desktop.
Save zerobias/85efeea9e6dc5ba1eda4a63af17574dc to your computer and use it in GitHub Desktop.
Private fields in js
//module version
var Module = (function (window) {
function privateFunction() {
console.log('pass');
};
var privateClass = function () {};
var publicClass = function () {};
publicClass.prototype.publicMethod = function () {
privateFunction(); // ...
};
return { // Экспортируем
publicClass: publicClass
};
}(this));
// Используем
(new Module.publicClass()).publicMethod();
//typical implementation
// our constructor
function Person(name, age){
this.name = name;
this.age = age;
};
// prototype assignment
Person.prototype = new function(){
// we have a scope for private stuff
// created once and not for every instance
function toString(){
return this.name + " is " + this.age;
};
// create the prototype and return them
this.constructor = Person;
this._protectedMethod = function (){
// act here
};
this.publicMethod = function() {
this._protectedMethod();
};
// "magic" toString method
this.toString = function(){
// call private toString method
return toString.call(this);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment