建構函式裡該不該驗證參數?該的。否則一個 new Book(123, ...) 就會一路攜帶著錯誤的型別往下跑,等到很遠的地方才爆開。本文用 Book 這個例子示範三種寫法。
<script type="text/javascript">
var Book = function (isbn, title, author) {
if (!this.checkIsbn(isbn)) {
throw new Error('Book: Invalid ISBN.');
}
this.isbn = isbn;
this.title = title || 'No title specified';
this.author = author || 'No author specified';
}
Book.prototype = {
checkIsbn: function (isbn) {
if (isbn == undefined || typeof isbn != 'string') {
return false;
}
return true; // 所有檢查都通過
},
display: function () {
alert("isbn:" + this.isbn + " title:" + this.title + " author:" + this.author);
}
};
var theHobbit = new Book('0-395-07122-4', 'The Hobbit', 'J. R. R. Tolkein');
theHobbit.display();
</script>
這裡做了兩件驗證:isbn 是否定義、是否為字串;title 與 author 則用 || 給了預設值。要注意 || 的副作用——傳入空字串、0、false 都會被視為「沒有值」而套用預設。若 0 是合法輸入,該改用 title != null ? title : 'default' 這種明確的判斷。
<script type="text/javascript">
var Book = function (isbn, title, author) {
this.setIsbn(isbn);
this.setTitle(title);
this.setAuthor(author);
}
Book.prototype = {
checkIsbn: function (isbn) {
if (isbn == undefined || typeof isbn != 'string') {
return false;
}
return true;
},
getIsbn: function () { return this.isbn; },
setIsbn: function (isbn) {
if (!this.checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.');
this.isbn = isbn;
},
getTitle: function () { return this.title; },
setTitle: function (title) { this.title = title || 'No title specified'; },
getAuthor: function () { return this.author; },
setAuthor: function (author) { this.author = author || 'No author specified'; },
display: function () {
alert("isbn:" + this.isbn + " title:" + this.title + " author:" + this.author);
}
};
var theHobbit = new Book('0-395-07122-4', '', 'J. R. R. Tolkein');
theHobbit.display();
</script>
這個版本的好處是驗證邏輯只有一份,而且建構時與之後任何時刻呼叫 setIsbn 都會經過同一道檢查。這在物件狀態會被反覆修改的場景中很重要——只在建構時驗證,等於之後所有的赋值都繞過了檢查。
代價是程式碼變長,而且 this.isbn 仍然是公開的,任何人都能直接 book.isbn = 123 繞道而過。要真正封鎖,得配合上一篇文章談的私有屬性手法。
<script type="text/javascript">
var Book = function (isbn, title, author) {
this.setIsbn(isbn);
this.setTitle(title);
this.setAuthor(author);
}
Book.prototype = {
// 約定俗成:底線開頭代表「內部使用,請勿直接呼叫」
_checkIsbn: function (isbn) {
if (isbn == undefined || typeof isbn != 'string') {
return false;
}
return true;
},
getIsbn: function () { return this.isbn; },
setIsbn: function (isbn) {
if (!this._checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.');
this.isbn = isbn;
},
getTitle: function () { return this.title; },
setTitle: function (title) { this.title = title || 'No title specified'; },
getAuthor: function () { return this.author; },
setAuthor: function (author) { this.author = author || 'No author specified'; },
display: function () {
alert("isbn:" + this.isbn + " title:" + this.title + " author:" + this.author);
}
};
// var theHobbit = new Book(123, '', 'J. R. R. Tolkein'); // 非字串,拋出異常
var theHobbit = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit.display();
</script>
底線前綴只是「約定」,執行期完全不強制。它的價值在於溝通:讀程式碼的人一眼就知道這個方法不是公開 API,不該在外部依賴它。這也是為什麼 `_checkIsbn` 從 prototype 上被拿掉、改由 setter 內部呼叫時,行為完全不變——它本來就不該被外部觸碰。
如果物件建立後就不會再改(value object),寫法一最簡潔。如果狀態會被反覆修改,寫法二或三更安全,因為驗證集中在 setter 裡。加上底線前綴是幾乎零成本的 Good Practice,建議 regardless 都加上。
ES6 之後,同樣的需求可以用 get/set 語法寫得更自然,讓 book.isbn 的讀寫自動經過方法:
class Book {
constructor(isbn, title, author) {
this.isbn = isbn; // 會觸發下面的 setter
this.title = title || 'No title specified';
this.author = author || 'No author specified';
}
set isbn(v) {
if (typeof v !== 'string') throw new Error('Book: Invalid ISBN.');
this._isbn = v;
}
get isbn() { return this._isbn; }
}
以上就是這篇的全部內容,希望對你的 JavaScript 開發有幫助。