1. 程式人生 > 實用技巧 >《學習javascript資料結構與演算法》類——例項

《學習javascript資料結構與演算法》類——例項

// 構造一個類
function Book(title, pages, isbn){
    this.title=title;
    this.pages=pages;
    this.isbn=isbn;
    //下2.
    // this.func2=function(){
    //     console.log(222);
    // }
}
// 新建一個類例項
var book=new Book('你不知道的JS', '50', '0001');
// 輸出資訊
console.log('書名:'+book.title);
console.log('頁數:'+book.pages);
console.log('編號:'+book.isbn);

  

// 更改資訊
book.title='資料結構與演算法';
console.log('新名字:'+book.title);

  

// 給類宣告函式
// 1.prototype 屬性使您有能力向物件新增屬性和方法
Book.prototype.func=function(){
    console.log(111);
}
book.func();

  

// 2.見上方註釋  內部定義函式
book.func2();

  

原始碼:

// 構造一個類
function Book(title, pages, isbn){
    this.title=title;
    this.pages=pages;
    this.isbn=isbn;
    this.func2=function(){
        console.log(222);
    }
}
// 新建一個類例項
var book=new Book('你不知道的JS', '50', '0001');
// 輸出資訊
console.log('書名:'+book.title);
console.log('頁數:'+book.pages);
console.log('編號:'+book.isbn);
// 更改資訊
book.title='資料結構與演算法';
console.log('新名字:'+book.title);
// 給類宣告函式
// 1.prototype 屬性使您有能力向物件新增屬性和方法
Book.prototype.func=function(){
    console.log(111);
}
book.func();
// 2.見上方註釋  內部定義函式
book.func2();