Skip to content

Instantly share code, notes, and snippets.

@chiro-hiro
Created March 9, 2020 03:04
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 chiro-hiro/17042d8da6276c6a1aded1cdc56c6f38 to your computer and use it in GitHub Desktop.
Save chiro-hiro/17042d8da6276c6a1aded1cdc56c6f38 to your computer and use it in GitHub Desktop.
// Human constructor
function Human(name) {
this.name = name;
}
// Define name as a property
Object.defineProperty(Human.prototype, 'name', {
set: function (value) {
if (typeof value !== 'string') {
throw new TypeError('Name value was not a string');
}
this._name = value
.split(' ')
.map(function (item) {
return item[0].toUpperCase() + item.substring(1);
})
.join(' ');
},
get: function () {
throw new Error('This value can not be read by this way');
}
});
// Get name of human
Human.prototype.getName = function () {
return this._name;
}
// Human race
Human.prototype.race = 'Terran'
// Man constructor
function Man(name) {
Human.call(this, name);
}
// Extends Man from Human
Man.prototype = Object.create(Human.prototype);
Man.prototype.gender = 'Male';
Man.prototype.constructor = Man;
const instanceHuman = new Human('chiro hiro');
console.log('My name is:', instanceHuman.getName(), 'Race:', instanceHuman.race);
const instanceMan = new Man('Some body we used to know');
console.log('My name is:', instanceMan.getName(), 'Race:', instanceMan.race, 'Gender:', instanceMan.gender);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment