Last active
October 20, 2016 15:37
-
-
Save zerobias/85efeea9e6dc5ba1eda4a63af17574dc to your computer and use it in GitHub Desktop.
Private fields in js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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