以下のコードでは説明できない動作に気付いています。私は誰かがなぜこれが起こっているのかについて私に啓発できることを願っています。Javascript:nullコンストラクタを使用して作成されたオブジェクトの未定義を示すデフォルトのプロトタイプフィールド
次のコード例は、JSFiddleでも読みやすくなっています。 https://jsfiddle.net/0b5rh4cg/
コード:
function Book() {
};
function Book (title, author) {
this.title = title;
this.author = author;
};
Book.prototype = {
title: "",
ISBN: "isbn",
length: 100,
genre: "genre",
covering: "covering",
author: "author",
currentPage: 0,
toString: function toString() {
console.log("toString Function");
console.log('Title: ' + this.title + '\n' +
'ISBN: ' + this.ISBN + '\n' +
'length: ' + this.length + '\n' +
'genre: ' + this.genre + '\n' +
'covering: ' + this.covering + '\n' +
'author: ' + this.author + '\n' +
'currentPage: ' + this.currentPage + '\n');
}
};
var book1 = new Book();
book1.toString();
var book2 = new Book("First edition", "Random");
book2.toString();
book1.toString() のtoString関数の出力 タイトル:未定義 ISBN:ISBN 長さ:100 ジャンル:ジャンル カバー:カバー 作成者:undefined currentPageに:0
book2.toString() のtoString関数の出力 タイトル:初版 ISBN:ISBN 長さ:100 ジャンル:ジャンル カバー:カバー 著者:ランダム 現在のページ:0
私の混乱は、著者とタイトルフィールドを囲んでいます。 nullコンストラクタでは、これらのフィールドのデフォルトはBookクラスのプロトタイプに設定されているものではなく、「未定義」です。
これを手伝ってくれてくれてありがとう。
Cheers、Cam。
JSはパラメータ多型をサポートしていません。第2の 'book'は最初のものを上書きします。 – georg