function init() { function Book(title, author) { this.title = title; this.author = author; } function toString() { var v = ""; for (s in this) { v+= s + ","; } return v; } Book.prototype.toString = toString; var book = new Book("Republic", "Plato"); document.write(book.toString() + "<br>"); Book.prototype.subject = "Philosophy"; document.write(book.toString() + "<br>"); }
title,author, subject,title,author,
关于prototype,一个奇怪的问题:
function Book(title, author) { this.title = title; this.author = author; } function getFields(O) { var v = ""; for (s in O) { v+= s + "=" + O[s] + ","; } return v; } var A = new Book("Ta", "Aa"); var B = new Book("Tb", "Ab"); document.write("--------------------------<br>"); document.write(getFields(A) + "<br>"); document.write(getFields(B) + "<br>"); B.pages = 508; B.price = "$20.50"; document.write("--------------------------<br>"); document.write(getFields(A) + "<br>"); document.write(getFields(B) + "<br>"); Book.prototype = B; document.write("--------------------------<br>"); document.write(getFields(A) + "<br>"); document.write(getFields(B) + "<br>"); document.write("--------------------------<br>"); document.write(getFields(Book.prototype) + "<br>"); var C = new Book("Tc", "Ac"); document.write("--------------------------<br>"); document.write(getFields(C) + "<br>");
function Book(title, author) { this.title = title; //实例变量 this.author = author; } Book.prototype.toString = function()//实例方法 { var a = "Book["; for (s in this) { a += s + "=" + this[s] + ";"; } a += "]"; return a; } Book.toString = function(book)//静态方法 { var a = "Book["; for (s in book) { a += s + "=" + book[s] + ";"; } a += "]"; return a; } var A = new Book("Ta", "Aa"); Book.KIND = "book";//静态变量 document.write(A.KIND + ";" + Book.KIND + "<br>"); document.write(A.toString() + "<br>"); document.write(Book.toString(A) + "<br>");