March 7, 201511 yr I've recently started teaching myself Javascript. I'd thought I'd see how object orientated prorgamming is handled in Javascript and as a result have written up this simple player creation and am just wondering whether I'm approaching this correctly? /** * Player Constructor */ function Player() { this.username; this.password; } /** * Player Username Setter * * @[member="param"] username * The Username to be set */ Player.prototype.setPlayerUsername = function(username) { // Check undefinied if(typeof username != 'undefined') { // Set Player Username this.username = username; } else { console.log("Please enter a valid parameter..."); } } /** * Player Password Setter * * @[member="param"] password * The Password to be set */ Player.prototype.setPlayerPassword = function(password) { // Check undefined if(typeof password != 'undefined') { // Set Player Password this.password = password; } else { console.log("Please entier a valid parameter...") } } /** * Player Username Getter * * @return The Current Player's Username */ Player.prototype.getPlayerUsername = function() { return this.username; } /** * Player Password Getter * * @return The Current Player's Password */ Player.prototype.getPlayerPassword = function() { return this.password; } /** * Create new Player * * @[member="param"] username * The Player's Username * @[member="param"] password * The Player's Password */ Player.prototype.create = function(username, password) { this.password = password; this.username = username; // new Player Object var player_to_create = new Player(); player_to_create.setPlayerUsername = username; player_to_create.setPlayerPassword = password; // log output console.log("Player Created: " + this.username + " " + this.password + "."); // save } Player.prototype.create(prompt("Enter a desired Username..."), prompt("Enter a desired Password...")); Thank you for any feedback. Edited March 8, 201511 yr by Responsive Designs
March 11, 201511 yr That looks right for prototyping. Although that said There's a lot of movement now away from simulating the 'classical' structure in JS seen as JS does not have classes, so in a sense there's no read need for constructor functions like the Player() constructor you have at the top of your code. Tutorials on this way of thinking are hard to find because JavaScript massively misunderstood which means most tutorials teach people to simulate classes in JavaScript which is totally unecessary. Read the book series 'You Don't Know JS' by Kyle Simpson he explains it there in great detail. Note ES6 is introducing classes but this is a bad thing, it's down to lazy, misinformed developers pushing for a classical method. People like Crockford, Kyle Simpson, other well known JS evangelists are advising to stay away from them. Edited March 11, 201511 yr by rbrtsmith
Create an account or sign in to comment