JavaScript

icon picker
OOJS

encapsulate封裝

將object的properties和method包進object裡

add method

const player1 = {
name: "Hedi",
color: "yellow",
isTurn: true,
play: function(){}
};

JSON(JS物件表示法) 比object多了property的""

this(用於object中的method)

const teacher = {
firstName : "Ashley",
lastName : "Boucher",
printName: function(){
console.log(this.firstName + this.lastName);
//this.firstName = this[firstName]
}
};

node.js使用

console.log(object名[property名]或.property名)

映出property的value
const ernie = {
animal: "dog",
age: "1",
breed: "pug",
bark: function(){
console.log( "Woof!" );
}
};

console.log( ernie["animal"] );
ernie["bark"]();

/*來點酷轉換*/
var prop = "breed";
ernie[prop];

class(syntactic sugar語法糖)

class的variable名的第一個字母要大寫!

constructor method(一種class method)

一般class method

class Pet {
constructor( type, breed, age, sound ) {
this.type = type;
this.breed = breed;
this.age = age;
this.sound = sound;
};

speak() {
console.log(this.sound);
};/*object instance的範例*/
};

const oly = new Pet( "dog", "bragle", 5, "woof" );
console.log(oly);
oly.speak();
Untitled.png

getters(以Date示範)

class Pet {
get activity() {
const today = new Date();
const hour = today.getHours();
if(hour > 8 && hour <= 20) {
return "playing";
}else {
return "sleeping";
}
}

const oly = new Pet();
console.log( oly.activity )
Untitled 1.png

setter

backing property

class Pet {
get owner() {
return this._owner;
}

set owner(owner) {
this._owner = owner;
console.log(`setter called: ${owner}`);
}
}
const oly = new Pet();
oly.owner = "Kai";
console.log(oly.owner);
console.log(oly);
Untitled 2.png

object interaction

class Pet {
constructor( type, breed, age, sound ) {
this.type = type;
this.breed = breed;
this.age = age;
this.sound = sound;
};

get owner() {
return this._owner;
}

set owner(owner) {
this._owner = owner;
}
};

class Owner {
constructor(name, address) {
this.name = name;
this.address = address;
}

get phone() {
return this._phone;
}
set phone(phone) {
const phoneNormalized = phone.replace(/[^0-9]/g, "");
this._phone = phoneNormalized;
}
}

const oly = new Pet( "dog", "bragle", 5, "woof" );
oly.owner = new Owner("Hedi", "No.17, 1 Alley");
oly.owner.phone = "0974-056-540";
console.log(oly.owner);
console.log(oly.owner.name);
console.log(oly.owner.phone);
Untitled 3.png

closure(已經有let可以改善這樣的問題)

a function with access to its own private variables.
function counter(noun) {
var count = 0;
return function() {
count++;
console.log(count + " " + noun);
};
};

var dogCount = counter("dogs");
var catCount = counter("cats");

dogCount();
catCount();
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.