// jshint esnext:true
// "use strict";
// esversion: 6
// jshint esversion: 6
// put this in .jshintrc in the root of the project
// {
// "esversion": 6
// }
// or put next line in the file
/*jshint esversion: 6 */
// Define property
function log(message) {
console.log(message);
}
let config = {
writable: true,
enumerable: true,
configurable: true
};
let defineProperty = function(obj, name, value) {
config.value = value;
Object.defineProperty(obj, name, config);
};
let man = Object.create(null);
defineProperty(man, 'sex', 'male');
defineProperty(man, 'fullName', function() {
return this.firstName + ' ' + this.lastName;
});
let kost = Object.create(man); // 'man' is a prototype for a newly created object
defineProperty(kost, 'firstName', 'Alex');
defineProperty(kost, 'lastName', 'Kost');
log(kost.sex);
log(kost.firstName);
log(kost.lastName);
log(kost.fullName());
log(Object.getPrototypeOf(kost));
// Assignment
var person = Object.create(null);
// instead of using defineProperty and specifying writable,
// configurable, and enumerable, we can just assign the
// value directly and JavaScript will take care of the rest
person['fullName'] = function() {
return this.firstName + ' ' + this.lastName;
};
// this time, let's make man's prototype person, so all
// men share the fullName function
var man = Object.create(person);
man['sex'] = "male"; // same as man.sex = "male";
var yehuda = Object.create(man);
yehuda['firstName'] = "Yehuda";
yehuda['lastName'] = "Katz";
log(yehuda.sex); // "male"
log(yehuda.fullName()); // "Yehuda Katz"
// Object literals
var alex = { firstName: "Alex", lastName: "Russell" };
// same as
var alex = Object.create(Object.prototype); // takes Object.prototype by default
alex.firstName = "Alex";
alex.lastName = "Russell"
// to create an object from literal with prototype passed:
var fromPrototype = function(prototype, object) {
var newObject = Object.create(prototype);
for (var prop in object) {
// we want to copy defined on the object itself, not on the protorype
if (object.hasOwnProperty(prop)) {
newObject[prop] = object[prop];
}
}
return newObject;
};