Last active
December 25, 2015 16:39
-
-
Save ggarnier/7007428 to your computer and use it in GitHub Desktop.
Javascript private functions
This file contains hidden or 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
// Reference: http://javascript.crockford.com/private.html | |
Test = function() { | |
function private() { | |
return "private"; | |
} | |
return { | |
public: function() { | |
return private(); | |
} | |
} | |
} | |
Test().public(); // "private" | |
Test().private(); // TypeError: Object #<Object> has no method 'private' | |
// Object-oriented style | |
Example = {}; | |
(function(namespace) { | |
function User(params) { | |
this.name = params.name; | |
this.birthday = params.birthday; | |
} | |
User.prototype = { | |
firstName: function() { | |
return this.name.replace(/ .*/, ""); | |
}, | |
age: function() { | |
return Math.floor(yearsBetween(this.birthday, new Date())); | |
} | |
} | |
var yearsBetween = function(startDate, endDate) { | |
var ms = endDate - startDate; | |
return ms / (1000*60*60*24*365); | |
} | |
namespace.User = User; | |
})(Example); | |
var user = new Example.User({name: "John Doe", birthday: new Date(1981, 1, 14)}); | |
user.name; // "John Doe" | |
user.birthday; // Sat Feb 14 1981 00:00:00 GMT-0300 (BRST) | |
user.firstName(); // "John" | |
user.age(); // 32 | |
// No way to access "yearsBetween" function | |
user.yearsBetween(user.birthday, new Date()); // TypeError: Object #<Object> has no method 'yearsBetween' | |
Example.User.yearsBetween(user.birthday, new Date()); // TypeError: Object function User(params) { this.name = params.name; this.birthday = params.birthday; } has no method 'yearsBetween' | |
Example.yearsBetween(user.birthday, new Date()); // TypeError: Object #<Object> has no method 'yearsBetween' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment