Chapter 6 花的時間相對前面的章節來的漫長不少
今天要來寫練習題了 真是可喜可賀(?
另外本書中文版共 441 頁,現在才到 127 頁XD
約讀完 1/4 左右而已
撰寫名為 Vec 的類別,表示二維空間中的向量
這個類別需要兩個參數 x,y,類型為數字,儲存在同一個名稱的屬性下
為 Vec 提供兩種方法:加法(plus)和減法(minus),這兩個方法會以另外的向量做參數,並回傳新的向量
新向量會是兩個向量各自具有的 x,y 值的和,或 x,y 值的差
在原型中新增getter方法的length屬性,負責計算向量長度,也就是原點(0,0)到點(x,y)的距離
class Vec {
constructor(x, y) {
this.x = x;
this.y = y;
}
set x(value) {
this.validateValue(value);
this._x = value;
}
set y(value) {
this.validateValue(value);
this._y = value;
}
validateValue(value) {
if (typeof value !== "number") {
console.error("invalid number");
}
}
plus(vecObject) {
const { _x, _y } = vecObject;
return new Vec(_x + this._x, _y + this._y);
}
minus(vecObject) {
const { _x, _y } = vecObject;
return new Vec(this._x - _x, this._y - _y);
}
get length() {
return Math.sqrt(Math.pow(this._x, 2) + Math.pow(this._y, 2));
}
}
let vec_1 = new Vec(2, 3);
let vec_2 = vec_1.plus(new Vec(3, 8));
let vec_3 = vec_2.minus(new Vec(22, 6));
console.log(vec_3.length);
建立一個類似 Set 的類別名為 Group
讓這個類別類似 Set ,具有 add/delete/has 三個方法
constructor 會建立一個空的 group
add 將值新增到 group 中
delete 將值從 group 中移除(如果存在於 group 中)
has 回傳一個 boolean 值,表示 parameter 是否存在於 group
為類別提供一個靜態方法 from ,該方法將一個可迭代物件作為 parameter
然後建立一個 group,包含物件在迭代過程中產生的值
讓 Group class 有迭代性,可使用 [Symbol.iterator] 建立迭代器
class Group {
#member = [];
[Symbol.iterator]() {
const value = Object.values(this.member);
let index = 0;
return {
next: () => {
if (index < this.instance.length) {
return { done: false, value: this.instance[index++] };
} else {
return { done: true };
}
},
};
}
add(value) {
if (!this.has(value)) {
this.#member.push(value);
}
}
delete(deleteVal) {
this.#member = this.#member.filter((v) => v !== deleteVal);
}
has(value) {
return this.#member.indexOf(value) === -1 ? false : true;
}
static from(iterableObject) {
let generatedGroup = new Group();
for (let value of iterableObject) {
generatedGroup.add(value);
}
return generatedGroup;
}
}
如果想忽略物件原型的屬性,使用物件的 hasOwnProperty 來取代 in operator 會是更健全的方法
但如果建立出來的 map 需要用到 hasOwnProperty 這個字,會發生什麼情況?
請想出一個方法
既可以在物件上呼叫 hasOwnProperty 又能讓它在使用這個名稱的情況下具有自己的屬性
**用 binding method **