Today I learn a code of Java Script.
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function() {
console.log(this.sound);
};
Animal.prototype.sharedValue = 1;
function Dog(name, sound) {
Animal.call(this, '개', name, sound);
}
Dog.prototype = Animal.prototype;
function Cat(name, sound) {
Animal.call(this, '고양이', name, sound);
}
Cat.prototype = Animal.prototype;
const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');
dog.say();
cat.say();
class Animal {
constructor(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
}
class Dog extends Animal {
constructor(name, sound) {
super('개', name, sound);
}
}
class Cat extends Animal {
constructor(name, sound) {
super('고양이', name, sound);
}
}
const dog = new Dog('멍멍이', '멍멍');
const dog2 = new Dog('왈왈이', '왈왈');
const cat = new Cat('야옹이', '야옹');
const cat2 = new Cat('냐옹이', '냐옹');
dog.say();
dog2.say();
cat.say();
cat2.say();
const array = [];
let text = array.length === 0
? '배열이 비어있습니다'
: '배열이 비어있지 않습니다.';
console.log(text);
Remember this 5 Falsy items.
console.log(!undefined);
console.log(!null);
console.log(!0);
console.log(!'');
console.log(!NaN);
console.log(true && 'hello'); // hello
console.log(false && 'hello'); // false
console.log('hello' && 'bye'); // bye
console.log(null && 'hello'); // null
console.log(undefined && 'hello'); // undefined
console.log('' && 'hello'); // ''
console.log(0 && 'hello'); // 0
console.log(1 && 'hello'); // hello
console.log(1 && 1); // 1
If the firt value is true in && evaluation, they will read 2nd value.(look upstair codes🙄)
If the first value is false in || evaluation, they read 2nd value.(like next codes)
const namelessDog = {
name: ''
};
function getName(animal) {
const name = animal && animal.name;
return name || '이름이 없는 동물입니다.';
}
const name = getName(namelessDog);
console.log(name); // 이름이 없는 동물입니다.
function calculateCircleArea(r = 1) {
return Math.PI * r * r;
}
const area = calculateCircleArea();
console.log(area); // 3.141592653589793
If you have to many 'if', you can write this that is more simple than that use 'if'.
function getSound(animal) {
const sounds = {
개: '멍멍!',
고양이: '야옹~',
참새: '짹짹',
비둘기: '구구 구 구'
};
return sounds[animal] || '...?';
}
console.log(getSound('개')); // 멍멍!
console.log(getSound('비둘기')); // 구구 구 구
const object = { a: 1 };
const { a, b = 2 } = object;
console.log(a); // 1
console.log(b); // 2
const array = [1, 2];
const [one, two] = array;
console.log(one);
console.log(two);