Wednesday, June 28, 2017

JS Basics

Obj literal, Constructor, Class and Properties

'use strict';

// object literal
var cat = {name: 'Fluffy', color: 'white'}
console.log(cat.color)
cat.age = 3
console.log('name=' + cat.name + ' and age=' + cat.age)
cat.speak = function() {console.log('Meoow')}
cat.speak()

// constructor
function Cat2(name, color) {
  this.name = name, 
  this.color = color
}
var sam = new Cat2('Sam', 'tabby');
console.log(sam.color)

// class
class Cat3 {
  constructor(name, color, age) {
    this.name = name,
    this.color = color,
    this.age = age
  }
  speak() {
    console.log('Meoow')
  }
}

var fred = new Cat3({first: 'Frederico', last: 'DeSoto'},'silver', 5)
fred.speak()

for (let property in fred) {
  console.log(property + ": " + fred[property])
}

console.log(JSON.stringify(fred));

Object.defineProperty(fred, 'fullName',
{
  get: function() {
    return this.name.first + " " + this.name.last  
  },
  set: function(val) {
    let parts = val.split(' ');
    this.name.first = parts[0];
    this.name.last = parts[1];
  }
})

console.log(fred.fullName)
fred.fullName = 'George Smiley'
console.log(fred.fullName)  // George Smiley